Page 1 of 1

Check first digit of a number using JS regular expression

Posted: Fri Dec 16, 2011 5:55 am
by Live24x7
Hi

I want the regular expression to check a form input. If the first digit of the 10 digit number is 0, it should prompt an alert
I wrote this code - but it is giving the alert if any of the 10 digits is 0.

Please suggest the regular expression for this.
regards

Code: Select all


x.toString().match(/^0*/) ) { alert("number must not start with zero");  return false; }


Re: Check first digit of a number using JS regular expressio

Posted: Fri Dec 16, 2011 6:26 am
by Weirdan
/^0+[^0]+/ - matches leading zeroes if they are followed by a non-zero digit. This way you allow zero itself but disallow leading zeroes.

Re: Check first digit of a number using JS regular expressio

Posted: Fri Dec 16, 2011 8:00 am
by Live24x7
@Weirdan - Thanks a lot.. it worked exactly the way it should have.

Regex is very confusing for me :roll:

Re: Check first digit of a number using JS regular expressio

Posted: Mon Dec 19, 2011 8:58 am
by Live24x7
Ok I have come across a problem - Earlier i had asked for a regular expression which would prevent users from entering 0 as the first number and weirdan had suggested
(/^0+[^0]+/)

It is working fine enough, except that it does not filter a number which is all zeros.

for e.g if a person enters 0235645 - it works fine.
but if a person enters 0000000 (all zeros) - it allows it through.

Why is it happening so ?