javascript - Phone Number Validator -
i have code validates phone number:
function phvalid() { var regexobj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; if (regexobj.test(subjectstring)) { var formattedphonenumber = subjectstring.replace(regexobj, "($1) $2-$3"); } else { alert("invalid number"); } }
i'm trying validate body of following html code:
<p class="normal">phone: <input type='text' id='ph' /> <input type='button' onclick="phvalid();" value="click" /> </p>
is function right or doing wrong?
you never define subjectstring
try this: http://jsfiddle.net/bfvxl/1/
function phvalid() { var regexobj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var subjectstring = document.getelementbyid("ph").value; if (regexobj.test(subjectstring)) { var formattedphonenumber = subjectstring.replace(regexobj, "($1) $2-$3"); } else { alert("invalid number"); } }
this run function, i'm not sure intention formattedphonenumber
block.
also, you'll need make sure onclick can access this. you'll have put js within body or within block gets ran after dom loaded.
edit: believe want formattedphonenumber
: http://jsfiddle.net/bfvxl/2/
edit2: new requirement in comment below... try this: http://jsfiddle.net/bfvxl/3/
function phvalid() { var subjectstring = document.getelementbyid("ph").value; subjectstring = subjectstring.replace(/[^\d]/g, ""); if (subjectstring.length == 10) { var regexobj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/; var formattedphonenumber = subjectstring.replace(regexobj, "($1) $2-$3"); document.getelementbyid("ph").value = formattedphonenumber; } else { alert("invalid number"); } }
and since regexobj
isn't being used validation in case, have /(\d{3})(\d{3})(\d{4})/
Comments
Post a Comment