Fix regex in jquery validation plugin with twitter bootstrap popover

I have this code that shows popover when there is a 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, a popover is not destroyed when there are no spaces. What am I doing wrong?

-one
jquery jquery-validate twitter-bootstrap
Apr 18 '13 at 17:41
source share
2 answers

This regular expression is valid for both white space and blank line.

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

+1
Apr 19 '13 at 5:09 on
source share

The rules declaration structure 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 should be the term ? And why regex inside term ?

  • If term is a rule, you cannot insert a rule ( regex ) inside a rule ( term ).
  • term not a "built-in" rule according to the documentation .
  • term also not a β€œnormal” rule according to your code.
  • If term is a name field, you cannot insert a field ( term ) inside 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 , this field checks if it returns false , the field will be invalid and an error will be displayed.

0
Apr 20 '13 at 15:22
source share



All Articles