Fix regex in jquery validation plugin with twitter bootstrap popover

末鹿安然 提交于 2019-12-13 08:04:42

问题


I have this code which shows a popover when there is a white space.

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

 $('#validateForm').validate({
     rules: {
         product: {
             required: true,
             term: {regex: /^\s*$/}
         }
     },
     messages: {
         product: {
             required: "A text is much",
             term: "Please avoid spaces"
         },
     },  

     showErrors: function (errorMap, errorList) {

         $.each(this.successList, function (index, value) {
             $('#'+value.id+'').popover('destroy');
         });


         $.each(errorList, function (index, value) {

             $('#'+value.element.id+'').attr('data-content',value.message).popover({
                 placement: 'top',
                 trigger: 'manual'
             }).popover('show');

         });

     }

 });

What happens is, the popover doesnt get destroyed once there is no whitespace. What am i doing wrong?


回答1:


This regular expression is valid for both white-space and for an empty string.

If you want to match only white-space, you should use this regex: /^\s+$/




回答2:


The structure of the rules declaration is as follows...

rules: {                       // <- rules:
    field_name: {              // <- name attribute of field                   
        rule_name: parameter,  // <- rule: parameter
        required: true,   // example 1
        min: 30           // example 2
    }
},

Now your code:

rules: {
    product: {
        required: true,
        term: {regex: /^\s*$/}
    }
},

What exactly is term supposed to be? And why is regex inside of term?

  • If term is a rule, you can't nest a rule (regex) inside of a rule (term).
  • term is not a "built-in" rule as per the documentation.
  • term is also not a "custom" rule as per your code.
  • If term is a field name, you can't nest a field (term) inside of a field (product).

Assuming your regex is correct, it should be like this...

rules: {
    product: {
        required: true,
        regex: /^\s*$/
    }
},

Also, remember that if your custom method returns true, the field validates, if it returns false, the field will fail validation and the error will display.



来源:https://stackoverflow.com/questions/16089725/fix-regex-in-jquery-validation-plugin-with-twitter-bootstrap-popover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!