html验证座机号码_使用Javascript验证电话号码

I'm working on a web form with several fields and a submit button. When the button is clicked, I am to verify that the required text boxes have been filled in and that the phone number is in the correct format. I can only accept 7 or 10 digit phone numbers, but characters such as (,), (-), etc are acceptable. If this box is empty or the phone number isn't in the correct format (not 7 or 10 numbers long, not a number) or has been left blank, I am supposed to add a red border around the text box. This border is supposed to remain in place until the user corrects the error.

I can't get this to work properly. I have tried several different ways to go about doing this, but have gotten several different types of errors. One way seemed to work, but the red border only displayed for a second and then disappeared and the value in the textbox was reset.

Here is my code and a link to a jsfiddle I've created:

Javascript:

function validateForm() {

return checkPhone();

}

function checkPhone() {

var phone = document.forms["myForm"]["phone"].value;

var phoneNum = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;

if(phone.value.match(phoneNum)) {

return true;

}

else {

document.getElementById("phone").className = document.getElementById("phone").className + " error";

return false;

}

}

HTML:

Phone Number:

JSFiddle:

解决方案

As for your regexp I guess it should be

^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}

But in general the presumption is not correct because one might enter something like

++44 20 1234 56789 or +44 (0) 1234 567890

it is better to do something like this

var phone = document.forms["myForm"]["phone"].value;

var phoneNum = phone.replace(/[^\d]/g, '');

if(phoneNum.length > 6 && phoneNum.length < 11) { return true; }

this will assure that entered value has 7 to 10 figures nevertheless what the formatting is. But you have to think about max length for number might be more than 10 as in the sample above.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值