Angular Form exact 10 alphanumeric letters pattern validation
Solution 1
You can use Angular Reactive Form Pattern Validators to achieve this.
validPattern = "^[a-zA-Z0-9]{10}$"; // alphanumeric exact 10 letters
this.projectForm = this.fb.group({
...
CIG: [null, [Validators.required, Validators.pattern(this.validPattern)],
Hope this address your issue.
Solution 2
You can also create your own custom validator function if you want more control over your error messages, and add it to your validators array. Such a function can be something like:
import { FormControl, ValidationErrors } from '@angular/forms';
const ALPHA_NUMERIC_REGEX = /^[a-zA-Z0-9_]*$/;
const ALPHA_NUMERIC_VALIDATION_ERROR = { alphaNumericError: 'only alpha numeric values are allowed' }
function alphaNumericValidator(control: FormControl): ValidationErrors | null {
return ALPHA_NUMERIC_REGEX.test(control.value) ? null : ALPHA_NUMERIC_VALIDATION_ERROR;
}
And add it to your validator list like so: like so:
[Validators.required, Validators.minLength(10),Validators.maxLength(10), alphaNumericValidator]
For more information on angular custom validators: custom validators
AndreaNobili
Updated on June 05, 2022Comments
-
AndreaNobili almost 2 years
I have the following problem with this specific use case of a reactive form field validation.
At the moment I only set this rule:
this.projectForm = this.fb.group({ ....................................................................................., ....................................................................................., ....................................................................................., CIG: [null, [Validators.required, Validators.minLength(10),Validators.maxLength(10)]],
at the moment I am checking if the value inserted into my CIG form field have exactly 10 charachers as lenght.
My problem is that I have to check also that this is an alphanumeric string (composed of exactly 10 characters).
So something like this is allowed: ABCED12345 but somethint like this is not allowed: ABCD-12345
How can I implement this behavior using Validators? I need to use REGEX or something like this?
-
hosam hemaily over 3 yearsyou saved my life