3

I am doing some validations in my form using AngularJS. In that there are a few fields where I need to accept only numbers. The range is from a single digit to n digits. I am planning to using regex in ngPattern attribute of AngularJS.

I need to accomplish the following things using the regex:

  • If it's a single digit, it should not be a 0. Can be anything between 1 to 9.
  • If it's a multi digit number, all numbers from 0 to 9 can be used in any position where not all numbers are 0 i.e. the total value of the input should not be 0

I am struggling to find a regex that will accept such pattern. Is it possible to accept such pattern using regex? Earlier I was thinking that at least the last number should be non-zero digit so that entries like 0000 will not be possible and will have to be 000x where x is anything from 1 to 9. But then this logic is flawed as it wont allow people to input values in multiples of 10.

How do I implement this validation?

2
  • Could you show the code that you have already tried? Commented Feb 4, 2016 at 7:48
  • @DaanvanHulst, I know this is wrong but this is what I was trying: ^([1-9]|[0-9]*)$. This also I have taken from a Stackoverflow answer and modified it a bit Commented Feb 4, 2016 at 7:49

2 Answers 2

2

I think, this is the one you're looking for:

^[0-9]*[1-9][0-9]*$

It matches on any number that contains at least one non-zero digit.

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

3 Comments

Hey worked perfectly. Can you please tell me the difference between your regex and ^([1-9]|[1-9][0-9]*)$ ? Both are giving same result. Just want to be sure about validation.
Your one doesn't match on anything starting with 0. Your one matches on one non-zero digit or any number starting with non-zero. My regex matches on any number that contain at leas one non-zero digit.
Thanks a lot!! Extremely helpful explanation and answer
1

An even better answer would be:

^(([1-9])|(0?([1-9]{1})[0-9]*))$

This is essentially the same as above, though it would allow 01 - 09 (and 01[##] ofcourse) as well, depending on your application.

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.