This is probably a beginner question but, I am trying to verify that a phone number entered in my form looks like 123-4567. Is there an easy way to do this?
yes :
--
get the input string :
tel_number = document.formname.textboxname.value
is there a - at the 4th place ?
tel_number.charAt(3)=="-"
are the 3 first chars numbers ?
isNan(ParseInt(tel_number.substring(0,3),10))
are the 4 last char numbers ?
isNan(ParseInt(tel_number.substring(4,7),10))
--
so your function will look like :
function validate_phone_number(){
var tel_number = document.formname.textboxname.value
if (tel_number.charAt(3)=="-" && !isNan(ParseInt(tel_number.substring(0,3),10)) && !isNan(ParseInt(tel_number.substring(4,7),10))) {
alert("ok this is correct"
return true
}
else {
alert("the phone number format is not correct"
return false
}
}
--
call the function with :
<form=formname onsubmit="javascript:return validate_phone_number()">
please enter your phone number : <input type=text name=textboxname>
</form>
--
let me know if this works !
note : you can do this with a regular expression as well, but it's a bit heavy only to validate a phone number !
Thanks! it works, but I get an error when I leave the field if the statement is true. The error say object expected and point to right before the if statement. The code still works though. I took out the alert for a correct entry, but that shouldn't cause an error. Also, it allows you to enter more onto the end. I there a way to make sure that the number only has 4 numbers after the "-" ?
heres an easier way to validate a phone number, using a regular expression:
<script>
function validate()
{
var rg = /^\d{3}\-\d{4}$/
fld = document.test.phone;
if(!rg.test(fld.value))
{
alert("Phone number must be in format: ###-####"
fld.focus();
fld.select();
return false;
}
}
The regular expression is probably the better way to go. The other way might give you an error if the number was shorter than 8 characters, and wouldn't catch numbers longer than 8 characters if the extra character were numeric.
Tracy Dryden
tracy@bydisn.com
Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.