Search code examples
angularangular-reactive-formsangular-validation

Angular Form exact 10 alphanumeric letters pattern validation


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?


Solution

  • 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.