How to validate white spaces/empty spaces? [Angular 2]
I think a simple and clean solution is to use pattern validation.
The following pattern will allow a string that starts with white spaces and will not allow a string containing only white spaces:
/^(\s+\S+\s*)*(?!\s).*$/
It can be set when adding the validators for the corresponding control of the form group:
const form = this.formBuilder.group({
name: ['', [
Validators.required,
Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/)
]]
});
Maybe this article can help you http://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/
In this approach, you have to use FormControl then watch for value changes and then apply your mask to the value. An example should be:
...
form: FormGroup;
...
ngOnInit(){
this.form.valueChanges
.map((value) => {
// Here you can manipulate your value
value.firstName = value.firstName.trim();
return value;
})
.filter((value) => this.form.valid)
.subscribe((value) => {
console.log("Model Driven Form valid value: vm = ",JSON.stringify(value));
});
}
You can create a custom validator to handle this.
new FormControl(field.fieldValue || '', [Validators.required, this.noWhitespaceValidator])
Add noWhitespaceValidator method to your component
public noWhitespaceValidator(control: FormControl) {
const isWhitespace = (control.value || '').trim().length === 0;
const isValid = !isWhitespace;
return isValid ? null : { 'whitespace': true };
}
and in the HTML
<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>