Reputation: 878
I need to create some kind of validation on my forms where I don't want user to be able to enter 1++ blank spaces inside fields. So, he can type space but it cannot be only spaces. This is how my validation looks like at the moment:
this.valForm = this.fb.group({
'firstName': [null, Validators.compose([Validators.required, Validators.maxLength(50)])],
'lastName': [null, Validators.compose([Validators.required, Validators.maxLength(50)])]
});
I dont know what pattern to use to create this type of validation. Thanks.
Upvotes: 4
Views: 13508
Reputation: 2771
You can just create a custom validator which checks for
userInputString.trim() !== ''
A validator is not much more than a function which takes a control and returns whether it is valid or not (either as a boolean or a promise/observable).
For more details check out any example out there for custom validators in angular 2+, e.g.
https://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html
Upvotes: 1
Reputation:
You can do
'firstName': [null, [Validators.required, Validators.maxLength(50), Validators.pattern(/^((?!\s{2,}).)*$/)]]
If you test it on Scriptular with the chain ^((?!\s{2,}).)*$
, you will find that
Hello darling // Matches
Hello darling // Doesn't match
This isn't something regexes should do : they're not good at it. A regex is supposed to find an occurence of your expression in a string, not the opposite. But still, they can do it.
If you want to know more, this is called a negative look-around.
Upvotes: 3