I used formBuilder in Angular2 and want to add validation pattern for not to allow \"only spaces\" in input.
try this, it will return false while sapce key press :
@Component({
selector: 'my-app',
template: `
<div>
<input class="form-control" type="number" formControlName="pinCode" placeholder="Pin Code"
(keydown.space)="$event.preventDefault()">
</div>
`,
providers: [myService]
})
visit for more Events :
https://developer.mozilla.org/en-US/docs/Web/Events
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 };
}
Use the following:
Validators.pattern(/^\S*$/)
hey i know i am very late in party but i have also faced same issue on which i have tired following code and it works :
as per my requirement, in form comment box should be has min 30 character and that character should be non-space.so to add validation i have used following code. I am using reactive forms. in ts file, add following code
comment:[''[Validators.required,Validators.minLength(30),Validators.pattern(/^((?!\s{2,}).)*$/)]]
Hey this sentence has one space between every word
//this will work
Hey this sentence has more than one space between every word
//this will throw err
I hope this will help somebody in future.