javascript教程 电话号码验证
下面的检查功能,如果电话号码是有效的。起初我们使用正则表达式和替换()方法
来清除任何间隔字符。下一步,我们使用isNaN()函数来检查的电话号码只包含数字
。最后我们检查字符串的长度和许可证,只有10个数字的电话号码。
function validatePhone(fld) {
var error = "";
var stripped = fld.value.replace(/[().- ]/g, '');
if (fld.value == "") {
error = "You didn't enter a phone number.n";
fld.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
error = "The phone number contains illegal characters.n";
fld.style.background = 'Yellow';
} else if (!(stripped.length == 10)) {
error = "The phone number is the wrong length. Make sure you
included an area code.n";
fld.style.background = 'Yellow';
}
return
error;
}
时间: 2024-09-25 07:51:57