我环顾四周,看到了许多正则表达式的例子,但不是我正在寻找的。我需要验证10位数,允许空格和破折号,但不能括号或其他字符。
以下是我目前正在使用的内容:
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/, '');
if (phone.value == "") {
document.getElementById('phone-error').innerHTML = "Please enter a phone number";
phone.style.background = 'Yellow';
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
phone.style.background = 'Yellow';
} else if (stripped.length < 10) {
var error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
phone.style.background = 'Yellow';
} else {
phone.style.background = 'White';
document.getElementById('phone-error').innerHTML = '';
}
谢谢!
答案 0 :(得分:2)
这就是我要做的事情:
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/\D+/, ''); // strips all non digit characters
if (stripped == "") {
document.getElementById('phone-error').innerHTML = "Please enter a phone number";
phone.style.background = 'Yellow';
error = '6';
} else if (phone.value.match(/[^\d() .-]/)) {
error = "5";
document.getElementById('phone-error').innerHTML = "The phone number contains illegal characters.";
phone.style.background = 'Yellow';
} else if (stripped.length < 10) {
error = "6";
document.getElementById('phone-error').innerHTML = "The phone number is too short.";
phone.style.background = 'Yellow';
} else {
phone.style.background = 'White';
document.getElementById('phone-error').innerHTML = '';
}
}
答案 1 :(得分:0)
你可以用空格替换\D
......这样你只剩下数字了。