Connecting Tech Pros Worldwide Forums | Help | Site Map

Numbers only validation using regular expression

Member
 
Join Date: Jun 2007
Location: Dundee, Scotland (From Chennai, India)
Posts: 46
#1: Jun 20 '07
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

acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#2: Jun 20 '07

re: Numbers only validation using regular expression


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.
Member
 
Join Date: Jun 2007
Location: Dundee, Scotland (From Chennai, India)
Posts: 46
#3: Jun 21 '07

re: Numbers only validation using regular expression


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
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#4: Jun 21 '07

re: Numbers only validation using regular expression


No problem. You're welcome. Post again if you have any more problems.
Member
 
Join Date: Jun 2007
Location: Dundee, Scotland (From Chennai, India)
Posts: 46
#5: Jun 21 '07

re: Numbers only validation using regular expression


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

Thanks
Reply