Search code examples
angularregextypescriptvalidationcustomvalidator

How to create a Validator.pattern that accepts ONLY numbers


I am working on an angular project, and I am trying to ensure that an input field only accepts positive integers between 1 and 28, however the regex I have tried is not marking the form field as invalid when letters are entered.

Here is my code:

setDateRegex = /^[0-9]*$/;

. . . 

scheduleSetDaysBefore: [null, [Validators.max(28), Validators.min(1), Validators.pattern(this.setDateRegex)]],

I have also tried the following regular expressions, and none of them are working.

/^[0-9]+$/

/^[0-9]+(\.?[0-9]+)?$/

And a few others I cannot remember.

EDIT

I just wanted to add, I have already achieved something similar by using a Valdidator.pattern() to check that an email has been entered in an acceptable format, as well as various length validators.


Solution

  • You can maybe use a custom validator, something like this

    // i have multiple custom validators so I am using them in a separate file.
    export class CustomValidators {
    
      static isNumbers(control: AbstractControl) {
    
        if (!(control.value)) {
          return null;
        }
    
        return String(control.value)
          .match(/^[0-9.]+$/) ? null : {'isNumbers': true};
      }
    }
    

    In your formBuilder, include this

    scheduleSetDaysBefore: [null, [Validators.max(28), Validators.min(1), CustomValidators.isNumbers]],
    
    

    And in your HTML, you can check for this error, apply invalid class on control maybe or show message

    <span class="error-message" *ngIf="form.get('scheduleSetDaysBefore').getError('isNumbers')">Please enter numbers only.</span>