jQuery custom validation rule with backslash
I'm trying to create a custom jquery validation rule to perform a regex on the value on a textbox. Here is the rule:
$.validator.addMethod("validateRegExp", function (value, element, pattern) {
console.debug("pattern: " + pattern);
var regex = new RegExp(pattern);
var isMatch = regex.test(value);
console.debug("value: " + value);
console.debug("result: " + isMatch);
return isMatch;
});
And here is the html:
<input type="text" class="{ "validateRegExp": "^\d{1,2}:\d{2}(\s)*(AM|am|PM|pm)$", messages: { "validateRegExp": 开发者_如何转开发"Invalid Time" } }" maxlength="8" value="8:00 AM" name="TuesdayStartTime" id="TuesdayStartTime" />
For some reason, when it calls the custom validateRegExp method, the pattern attribute is set to:
^d{1,2}:d{2}(s)*(AM|am|PM|pm)$
As you can see, the backslashes have been removed. I can even put in 2 or 3 backslashes where each one should go and still when it goes into this method, all backslashes are filtered out. How do I get this working?
The answer was to put in 4 back slashes for each 1 that I want in the regex, as it gets parsed twice, once when programmatically created, and secondly by jquery.metadata.
title.append($("<div class='section'><input id='" + id + "_EndTime' name='" + id + ".EndTime' value='" +
(day.EndTime ? day.EndTime : "") + "' type='text' maxlength='8' " +
utils.addValidationRuleHtml("validateRegExp", "^\\\\d{1,2}:\\\\d{2}(\\\\s)*(AM|am|PM|pm)$", "Invalid Time") + " /></div>"));
You seem to be trying to have double-quotes within double-quotes. Change some to single quotes. e.g.
<input type="text"
class="{ validateRegExp: '^\d{1,2}:\d{2}(\s)*(AM|am|PM|pm)$',
messages: { validateRegExp: 'Invalid Time' }
}"
maxlength="8"
value="8:00 AM"
name="TuesdayStartTime"
id="TuesdayStartTime" />
Not sure if that will help (I've never seen a class specified this way before) but it can't make it any worse.
精彩评论