To incorporate a validation pattern that restricts the use of only whitespace in input for Angular2, you can follow these steps:
/^\s*$/
import { AbstractControl, ValidatorFn } from '@angular/forms';
export function noWhitespaceValidator(): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
const input = control.value;
const hasWhitespace = input && /^\s*$/.test(input);
return hasWhitespace ? {'whitespace': {value: input}} : null;
};
}
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace-validator';
@Component({
selector: 'app-root',
template: `
<form [formGroup]="form">
<input formControlName="input">
<div *ngIf="form.get('input').hasError('whitespace')">
Only whitespace characters are not allowed.
</div>
</form>
`
})
export class AppComponent {
form: FormGroup;
constructor() {
this.form = new FormGroup({
input: new FormControl('', {
validators: [
Validators.required,
noWhitespaceValidator()
]
})
});
}
}
In this example, the noWhitespaceValidator
is used alongside the required validator to ensure that the input field cannot be empty or contain only whitespace characters. If the input fails the validation, the error message will be displayed in the template.
Asked: 2021-08-14 11:00:00 +0000
Seen: 9 times
Last updated: May 01 '21