验证文本字段的前2个字符

时间:2012-12-28 14:41:48

标签: javascript jquery html5 jquery-mobile

我有一个文本框,用户需要输入他/她的手机号码。但是,我需要验证前2个数字(字符),以确保移动电话号码的格式正确(作为验证规则之一)。

手机号码必须以下列任意两位数字开头:

44xxxxxx 55xxxxxx 65xxxxxx 78xxxxxx

有谁能告诉我如何验证前两个字符编号并检查它们是否是上面提到的选项之一?

修改 这是我曾经尝试过的,但它不起作用:

HTML

<input id="mob" name="mob" type="tel" placeholder="Enter your mobile number">
<a href="#" id="validate">Validate</a>

JS

var mobile_prefix = $('#mob').subsubstr(0,2);
$('#validate').click(function(){
if (mobile_prefix == 44||55||65||78) {
alert('correct');
}
else {
    alert('incorrect');
}
});

4 个答案:

答案 0 :(得分:7)

我认为.match()有你想要的东西。只需了解一些regular expressions

if (StringFromSelectField.match(/^(44|55|65|78)/)) {
    //do something
}

答案 1 :(得分:2)

使用正则表达式可能是最简单的:

({phone number}).match(/^(44|55|65|78).*$/)

答案 2 :(得分:1)

使用javascript中的substring

var FirstTwoLetters = TextFromYourInput.substring(0,2);

然后你可以将前两个字母与你的模式进行比较。

答案 3 :(得分:0)

所以输入字段的第一个变量;我的方式;) 首先检查输入是否为空并且有3个或更多符号。 最后是变量,我最后使用它来允许form.submit()。 如果你想要,你可以在每次获得val()$.trim(postcode.val()) != ''

之前添加
var postcode = $('#post_code');
        if(postcode.val() != '' && postcode.val().length > 2){
            var shortPostCode = postcode.val().substring(0,2);
            var validPostCode = /^(EH|KY)/;
            if(!shortPostCode.match(validPostCode)){
                postcode.after('<span class="error">Post code must start with EH</span>');
                dataValid = false;
            }
        }
相关问题