Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 : Validators.pattern() not working

Tags:

angular

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.

like image 713
Dinesh Shah Avatar asked Feb 22 '17 13:02

Dinesh Shah


People also ask

How do you use a validator pattern?

According to given regex, validation will be performed. pattern attribute can be used with formControl , ngModel and formControlName . To work with FormGroup and FormBuilder we will get pattern from Validators by calling Validators. pattern .

What is Validatorfn in angular?

ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null.

How do you set a validator dynamically?

We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.

How will you add validators in FormControl?

Adding async validators to reactive formslink To use an async validator in reactive forms, begin by injecting the validator into the constructor of the component class. Then, pass the validator function directly to the FormControl to apply it.


1 Answers

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

Validators.pattern('^[a-zA-Z]+$') 
like image 158
Günter Zöchbauer Avatar answered Sep 21 '22 01:09

Günter Zöchbauer