I used formBuilder in Angular2 and want to add validation pattern for not to allow "only spaces" in input.
FormBuilder allows us to explicitly declare forms in our components. This allows us to also explicitly list each form control's validators.
Building a custom validator In it's simplest form, a validator is really just a function that takes a Control and returns either null when it's valid, or and error object if it's not.
Use the following:
Validators.pattern(/^\S*$/)
space Not allowed
let nospacePattern = [a-zA-Z0-9]
As per requirement in comment section.
need pattern not to allow only spaces. (space in between words are allowed).but when user enter spaces in input and try to save it then it should not allow to save
Validators.pattern(".*\\S.*[a-zA-z0-9 ]");
Better and Cleaner way to use custom validation pattern like below -
controlName: ['', [Validators.required, this.noWhitespaceValidator]],
....
....
noWhitespaceValidator(control: FormControl) {
const isWhitespace = (control && control.value && control.value.toString() || '').trim().length === 0;
const isValid = !isWhitespace;
return isValid ? null : { 'whitespace': true };
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With