Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 915
AndreaNobili Avatar asked Aug 27 '26 15:08

AndreaNobili


2 Answers

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.

like image 50
Kamran Khatti Avatar answered Aug 30 '26 09:08

Kamran Khatti


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

like image 41
ben marder Avatar answered Aug 30 '26 10:08

ben marder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!