Home > database >  How to make a validation pattern in Angular to check that the input is between two numbers (0-130)
How to make a validation pattern in Angular to check that the input is between two numbers (0-130)

Time:12-01

I have a form and I want to add a pattern validator to one of the input boxes to only allow numbers between 0 and 130.

I am new in coding and I have no clue what I am doing. I want the input box to get red or have some error message if another number / letters are written.

CodePudding user response:

you can use pattern validation :

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

or you can define a validator 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(0, 130)],

CodePudding user response:

You can use the following angular built-in validators:

field = new FormControl([minLength(0), maxLength(130]);

Is faster than a regex, and the alternative is building your own validator like Chady BAGHDADI said. You can find more info in https://angular.io/api/forms/Validators

  • Related