469,612 Members | 1,553 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,612 developers. It's quick & easy.

Numbers only validation using regular expression

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
4 20782
acoder
16,027 Expert Mod 8TB
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
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
16,027 Expert Mod 8TB
No problem. You're welcome. Post again if you have any more problems.
Jun 21 '07 #4
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.

Similar topics

4 posts views Thread by Geoff Soper | last post: by
3 posts views Thread by Skippytpe | last post: by
2 posts views Thread by Coleen | last post: by
5 posts views Thread by JIM.H. | last post: by
1 post views Thread by Jim Dornbush | last post: by
2 posts views Thread by jack | last post: by
reply views Thread by devrayhaan | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.