问题
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
termis a rule, you can't nest a rule (regex) inside of a rule (term). termis not a "built-in"ruleas per the documentation.termis also not a "custom" rule as per your code.- If
termis a fieldname, 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