Check first digit of a number using JS regular expression

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

Check first digit of a number using JS regular expression

Post 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; }

User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

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

Post 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.
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

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

Post by Live24x7 »

@Weirdan - Thanks a lot.. it worked exactly the way it should have.

Regex is very confusing for me :roll:
Live24x7
Forum Contributor
Posts: 194
Joined: Sat Nov 19, 2011 9:32 am

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

Post 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 ?
Post Reply