3

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.

5
  • 1
    I don't have anything to test right now. How about Validators.pattern(/^-?[0-9]+$/) Commented Jun 13, 2020 at 13:14
  • Thanks. It works partially, except for negative, it allows negative numbers. Commented Jun 13, 2020 at 13:24
  • Found: ^[-+]?\d*$. Adapted from: regexlib.com/… Commented Jun 13, 2020 at 13:33
  • 1
    You never told that negative is not allowed. Just remove -? for positive numbers only. Commented Jun 13, 2020 at 13:43
  • Sorry, my bad, it is time to eat! Thanks! Commented Jun 13, 2020 at 13:44

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.