By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,533 Members | 2,102 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,533 IT Pros & Developers. It's quick & easy.

Numbers only validation using regular expression

P: 46
Hi,

I have seen various online resources and tuturials. I ahve written a piece of code but it does not seem to work

[code: text]
Problem defined:
If not number entered (as not mandartory)
ignore
else
if yes then remove the spaces
remove the hypens
check if the values entered now are only numbers using regualr expression
if not, then return fasle
else return true
[code: text]

The bit of Javascript I have written:
[code:javascript]

fucntion checkDetails()
{
var contactNumber=document.frmUser.contactNumber.value ;

if (contactNumber.length != 0)

{
var telnum = contactNumber;

// Remove spaces from the telephone number to help validation
while (telnum.indexOf(" ")!= -1)
{
telnum = telnum.slice (0,telnum.indexOf(" ")) + telnum.slice (telnum.indexOf(" ")+1);
}

// Remove hyphens from the telephone number to help validation
while (telnum.indexOf("-")!= -1)
{
telnum = telnum.slice (0,telnum.indexOf("-")) + telnum.slice (telnum.indexOf("-")+1);
}

// Now check that all the characters are digits
exp = /^[0-9]$/;
if (exp.test(telnum) != true)
{
alert("Please enter only numbers with area code - For example: 01382000000");
}
return false

}
return true

}

[code: javascript]

Now if I enter nothing it works if otherwise it just doesnt add and keeps poping the alreat message even if I have only entered numbers.

Gone through my untrained eyes several time but not able to find the culprit bit.

Would be great if someone can point me out to it.

Thanks in advance
Sree
Jun 20 '07 #1
Share this Question
Share on Google+
4 Replies


acoder
Expert Mod 15k+
P: 16,027
Your regular expression needs to be /^\d+$/ (notice the +) - see link. You can also use the replace method (described in that link) to remove strings and hyphens instead of your method.
Jun 20 '07 #2

P: 46
Thanks acoder,

It works, I was using the wrong regular expression, thanks for pointing out...

The tutorial was also very helpful.

Thanks once again,
Sree
Jun 21 '07 #3

acoder
Expert Mod 15k+
P: 16,027
No problem. You're welcome. Post again if you have any more problems.
Jun 21 '07 #4

P: 46
Nope just one change and the whole code was working ;)

Thanks
Jun 21 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.