How to validate white spaces/empty spaces? [Angular 2]
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>
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)); });}
Prevent user to enter space in textbox in Angular 6
<input type="text" (keydown.space)="$event.preventDefault();" required />