regexangularformbuilderangular-custom-validators

Regex expression with Validators.pattern for just integer number


I am trying to create a validator for only integers (e.g., 60) using Regex. Here how I am trying to do it:

meter: ["", Validators.required, Validators.pattern(/[0-9]/)]

It does not work, but I have to say I am not familiar with this technique. Anyone could shed some light on how I could modify this expression to accept just integers? This number is for height, and the height is devided into meters and centimeter.

I have searched, but I could find for decimals and so, somehow, maybe because it is too trivial, for just integers, I cannot find, in fact, I have found yesterday here, but I cannot find the answer anymore I have found, I was looking for another thing.


Solution

  • First of all, you don't need a custom validator to do this, as regular expression validation is already a built-in validator.

    Secondly, the way you apply validators to your form controls depending on either you are using template-driven forms or reactive forms.

    If you are using template-driven forms (which is commonly used for Angular beginners), simply make your input control template look like this:

    <input type="number" name="meter" required pattern="[0-9]" [(ngModel)]="meter">
    

    If you are using reactive forms, just assign both "required" and "pattern" validator to your form control.

    <input type="number" [formControl]="myControl">
    
    myControl = new FormControl(null, [
        Validators.required,
        Validators.pattern("[0-9]+")
      ]);
    

    When using it in a reactive form control, you can pass in either a string or a regex object, there are differences between them as stated in official docs:

    If a string is passed, the ^ character is prepended and the $ character is appended to the provided string (if not already present), and the resulting regular expression is used to test the values.

    Lastly, a Stackblitz example attached to show simple usage of this validator in both template/reactive forms.

    https://stackblitz.com/edit/angular-ivy-neux3n