0

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.

TreyBCollier
  • 213
  • 3
  • 8
  • See [this post](https://stackoverflow.com/questions/41465542/angular2-input-field-to-accept-only-numbers) and there are many more, doesn't anything work? – Wiktor Stribiżew Aug 20 '21 at 17:23

2 Answers2

0

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>

amnah
  • 444
  • 2
  • 6
-1

The below validator only numbers only. Try this, it may work: ^[0-9]*$

CinCout
  • 9,486
  • 12
  • 49
  • 67