I am trying to validate input type="text"
using a pattern. I want text only.
Component :
this.from = this.fb.group({
name: ['',[Validators.required,Validators.pattern('/^[a-zA-Z]+$/')]],
});
Html :
<input type="text" formControlName="name"/> // omitting other html template like from tag.
The above pattern validation is not working for me. It always returns an invalid state.
Pass pattern as string, without /
which are the delimiters for regex
Validators.pattern('^[a-zA-Z]+$')
Remember to not do this:
Validators.pattern("[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}")
The gotcha is that you need a double backslash before the s to defeat string escape thus:
Validators.pattern("[A-Z]{1,2}[0-9][0-9A-Z]?\\s?[0-9][A-Z]{2}")
emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
this.form = fb.group({
Email : new FormControl({value: null}, Validators.compose([
Validators.required,
Validators.pattern(this.emailRegex)]))
});
I had this same problem with a different pattern:
^\d{1,4}$
And I was using it like this:
Validators.pattern("^\d{1,4}$") // wrong
The problem is that the backslash \
has to be escaped, so the correct form is:
Validators.pattern("^\\d{1,4}$") // correct
This is what I've found when using Validators.pattern()
:
Works
Validators.pattern('[a-z]{2}')
Validators.pattern(/^[a-z]{2}$/)
Doesn't work
Validators.pattern(/[a-z]{2}/i)
Validators.pattern(/[a-z]{2}/)
Text + 'space'
Validators.pattern('[a-zA-Z ]*')