简体   繁体   中英

Jquery validate plugin not working for addmethod

I am using jquery validate plugin. While trying to use mobile number regular expression validation it is not working. Could anyone help me on that.

 $(document).ready(function() {
    $.validator.addMethod(
      "regex",
      function(value, element, regexp) {
          var check = false;
          var re = new RegExp(regexp);
          return this.optional(element) || re.test(value);
      },""
);
});


            $("#membership_form").validate({
            rules: {
                "data[mobile]": {
                    required: true,
                    number: true,
                    regex: '/^\2547\d{8}/'                                   
                },
            },
            messages: {
                "data[mobile]": {
                    required: 'Phone number is required',
                    regex:'Please match the pattern'
                },
            },


 });

Try this

The only suspect I see is the name in validate method. It seems you are trying to validate with wrong name as data[mobile] .

 $.validator.addMethod( "regex", function(value, element, regexp) { var check = false; var re = new RegExp(regexp); return this.optional(element) || re.test(value); },""); $("#membership_form").validate({ rules: { "Mobile": { required: true, number: true, regex: '/^\\2547\\d{8}/' }, }, messages: { "Mobile": { required: 'Phone number is required', regex:'Please match the pattern' }, } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script> <form id="membership_form"> <input name="Mobile" type="text"/> <input type="submit"/> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM