jQuery custom validation: phone number starting wi

2019-01-24 21:50发布

I have a form in which you have to input your phone number and other fields.

I'm validating the form with jQuery Validate.

To validate the phone number field I do:

rules: {
    phone: {
    required: true,
        minlength: 9,
        number:true
    },..

But I need to check also that phone starts with 6.

How can I do that?

3条回答
放荡不羁爱自由
2楼-- · 2019-01-24 22:18

You can also try simple Javascript function

"Hello World!".startsWith("He"); //true

Note: This comment/code is for those who are not using jquery validate.

查看更多
Viruses.
3楼-- · 2019-01-24 22:24

I think you will need to add a custom validator.

$.validator.addMethod("phoneNumber", function(uid, element) {
    return (this.optional(element) || uid.match(phone number regex));
}
查看更多
倾城 Initia
4楼-- · 2019-01-24 22:31

You can add a custom validator

jQuery.validator.addMethod("phoneStartingWith6", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
    return this.optional(element) || phone_number.match(/^6\d{8,}$/);
}, "Phone number should start with 6");

and use it like this:

rules: {
    phone: {
        required: true,
        minlength: 9,
        phoneEnding6: true
    },..

You need to edit the regex inside phone_number.match to suit your requirements.

查看更多
登录 后发表回答