Angular 2 : Validators.pattern() not working

2020-02-08 13:01发布

问题:

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.

回答1:

Pass pattern as string, without / which are the delimiters for regex

Validators.pattern('^[a-zA-Z]+$')


回答2:

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}")


回答3:

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)]))
});


回答4:

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


回答5:

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}/)


回答6:

Text + 'space'

Validators.pattern('[a-zA-Z ]*')


标签: angular