I used formBuilder in Angular2 and want to add validation pattern for not to allow \"only spaces\" in input.
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 };
}