jQuery custom validation: phone number starting with 6

前端 未结 3 876
南笙
南笙 2020-12-17 05:17

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 fi

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-17 05:56

    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.

提交回复
热议问题