【问题标题】:Fix regex in jquery validation plugin with twitter bootstrap popover使用 twitter bootstrap popover 修复 jquery 验证插件中的正则表达式
【发布时间】:2013-04-18 17:41:09
【问题描述】:

我有这段代码,当有空格时会显示一个弹出框。

$.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');

         });

     }

 });

发生的情况是,一旦没有空格,弹出框就不会被破坏。我做错了什么?

【问题讨论】:

标签: jquery twitter-bootstrap jquery-validate


【解决方案1】:

这个正则表达式对空格和空字符串都有效。

如果你只想匹配空格,你应该使用这个正则表达式:/^\s+$/

【讨论】:

    【解决方案2】:

    rules声明的结构如下...

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

    现在你的代码:

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

    term 到底应该是什么?为什么regexterm 里面?

    • 如果 term 是规则,则不能在规则 (term) 内嵌套规则 (regex)。
    • term 不是“内置”rule as per the documentation
    • 根据您的代码,term 也不是“自定义”规则。
    • 如果 term 是字段 name,则不能在字段 (product) 内嵌套字段 (term)。

    假设你的正则表达式是正确的,它应该是这样的......

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

    另外,请记住,如果您的自定义方法返回 true,则该字段会验证,如果返回 false,则该字段将验证失败并显示错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多