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) {
    return (control.value || '').trim().length? null : { 'whitespace': true };       
}

and in the HTML

<div *ngIf="yourForm.hasError('whitespace')">Please enter valid data</div>

Leave a Comment