Home > front end >  How to validate two specific lengths - Reactive forms
How to validate two specific lengths - Reactive forms

Time:11-28

I am doing a field validation in Angular component. There is a one field like it should allow to enter either 6 or 8 length of any characters. Usually minLength(6), maxLength(8) will work if it is 6 to 8 in between but length 7 should not allow here. I can do custom validation, but out of curiosity I'm looking is there any way to handle this kind of scenario. Thanks in advance.

'myField': ['', [Validators.minLength(6), Validators.maxLength(8)]]

CodePudding user response:

The only way without a custom validator I can think of is Validator.pattern , which takes a regular expression. Something like that:

myControl: FormControl = new FormControl(undefined, [
    Validators.pattern('^.{6}$|^.{8}$'),
  ]);

Or for only alphabetical:

myControl: FormControl = new FormControl(undefined, [
    Validators.pattern('^[a-zA-Z]{6}$|^[a-zA-Z]{8}$'),
  ]);

CodePudding user response:

No need to create a custom validator for your case; you can use pattern Validators.

'myField': ['', [Validators.pattern('^(?=(?:.{6}|.{8})$).*$')]]

CodePudding user response:

you can use a custom validators with a between function like that :

function between(x, min, max) {
  return x >= min && x <= max;
}


function ratingRange(min: number, max: number): 

    ValidatorFn {
      return (c: AbstractControl): { [key: string]: boolean } | null => {
        if (c.value !== null && (isNaN(c.value) || c.value < min || c.value > max) || this.between(c.value , min , max)) {
          return { range: true };
        }
        return null;
      };
    }

then :

 'myField': [null, ratingRange(6, 8)],
  • Related