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.
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 .
ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null.
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.
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.
Pass pattern as string, without /
which are the delimiters for regex
Validators.pattern('^[a-zA-Z]+$')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With