我需要在 javascript 中验证电话号码。 要求是:
they should be 10 digits, no comma, no dashes, just the numbers, and not the 1+ in front
这就是我写的
function validatePhone(field,alerttxt) {
with (field) {
if(value.length > 10) {
alert(alerttext);
return false;
}
for(i = 0; i < value.length; i++) {
if(parseInt(value[i]) == NaN) {
alert(alerttxt);
return false;
}
}
return true;
}
}
function validateForm(thisform) {
if (validatePhone(phone,"Invalid phone number")==false) {
phone.focus();
return false;
}
}
}
<form action="post.php" method="post" id="contactform" onsubmit="return validateForm(this)">
<ol>
<label for="phone">Your phone <span class="red"></span></label>
<input id="phone" name="phone" class="text" />
</li>
</ol>
</form>
但是,显然它不起作用。
我如何编写 validatePhone()
函数才能使其正常工作?
最佳答案
phone = phone.replace(/[^0-9]/g, '');
if(phone.length != 10) {
alert("not 10 digits");
} else {
alert("yep, its 10 digits");
}
这将根据您的要求进行验证和/或更正,删除所有非数字。
关于Javascript 电话号码验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2386054/