jQuery使用RegEx验证电话号码 [英] jQuery validate phone number with with RegEx
问题描述
我有一个简单的ajax表单,我正在尝试验证它
I have a simple ajax form and I'm trying to validate that it
- 有一个值
- 该值是一个10位数字
我正在尝试使用RegEx这样做。这是我到目前为止所拥有的。
I'm trying to use RegEx to do so. Here is what I have so far.
var reg = new RegExp("/[0-9]{10}/");
$("#call_form").bind("submit", function() {
if ($("#call_number").val().length < 1 && reg.test($("#call_number").val())) {
$("#call_error").show();
return false;
}
});
我知道问题与RegExp有关,好像我删除了它验证的这部分代码该框有一个值。
I know the problem has to do witht he RegExp as if I remove this portion of the code it validates that the box has a value.
编辑:这是我正在使用的最终正则表达式
EDIT: Here is the final regex I'm using
var regEx = new RegExp("/[0-9]/");
$("#call_form").bind("submit", function() {
if ($("#call_number").val().length != 10 && !$("#call_number").val().match(regEx)) {
$("#call_error").show();
$.fancybox.resize();
return false;
}
});
编辑2
使用这里的建议就是我的意思允许使用空格和破折号,然后在检查时被剥离
EDIT 2 Using the suggestions here is what i'm usign which allows spaces and dashes that then get stripped on check
$("#call_form").bind("submit", function() {
var Phone = $("#call_number").val().replace(/\D+/g,'');
if (Phone.length != 10) {
$("#call_error").show();
$.fancybox.resize();
return false;
}
});
推荐答案
你的正则表达式适用于我......你可以将它缩短到 / [0-9] {10} /
。
Your regex works fine for me... you could shorten it to just /[0-9]{10}/
.
你的问题在这里:
$(#call_number)。val()。length< 1
。如果数字是10个字符长,它永远不会少于1,不是吗?
$("#call_number").val().length < 1
. If the number is 10 characters long, it will never be less than 1, no?
你可能意味着这样的事情:
You probably meant something like this:
$(#call_number)。val()。length === 10
这篇关于jQuery使用RegEx验证电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!