我有一个jQuery Validate的正则表达式规则设置。但是,一旦突出显示方法被触发,无论我在字段中键入什么,我似乎无法触发Unhighlight方法。
以下是一个示例:
<html>
<head>
<title>test</title>
<link rel="stylesheet" href="http://eat-sleep-code.com/style/jquery-ui.min.css" />
<link rel="stylesheet" href="http://eat-sleep-code.com/style/bootstrap.min.css" />
<link rel="stylesheet" href="http://eat-sleep-code.com/style/bootstrap-theme.min.css" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://eat-sleep-code.com/scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="http://eat-sleep-code.com/scripts/jquery.validate.min.js" defer="defer"></script>
</head>
<body>
<form>
<fieldset>
<legend>
Example Form
</legend>
<ol>
<li id="ExampleInputRow">
<input type="text" id="ExampleInput" name="ExampleInput" class="form-control" maxlength="256" />
</li>
</ol>
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function () {
var lettersNumbersOnlyMinMaxCharactersRegex = '/^[a-z0-9]{8,32}$/ig';
$.validator.addMethod('lettersNumbersOnlyMinMaxCharacters', function (value, element, parameter) {
return value.match(lettersNumbersOnlyMinMaxCharactersRegex);
}, '');
$.validator.setDefaults({
errorPlacement: function(error, element){
$(error).insertBefore($(element));
},
highlight: function(element, errorClass) {
$(element).parent().removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent().removeClass('has-error').addClass('has-success');
},
invalidHandler: function(event, validator) {
setTimeout(function(){
$('input:text').blur();
$('input:password').blur();
$('textarea').blur();
}, 10);
},
onkeyup: function (element) {
$('#ExampleInput').valid();
}
});
var validator = $("form").validate({
rules: {
ExampleInput: {lettersNumbersOnlyMinMaxCharacters: true}
},
messages: {
ExampleInput: {lettersNumbersOnlyMinMaxCharacters: "You must enter between 8 and 32 numbers and letters."}
}
});
function Validate() {
return $('form').valid();
}
});
</script>
如果我输入8个字母,则应匹配正则表达式并清除错误消息。但这不会发生。我在谷歌Chrome开发者工具中设置了一个关于unhighlight方法内容的断点,但它似乎永远不会被击中。
答案 0 :(得分:2)
因为您没有将正则表达式传递给匹配项,所以您传递的是字符串
var lettersNumbersOnlyMinMaxCharactersRegex = /^[a-z0-9]{8,32}$/ig;
演示:Fiddle
此外,无需编写新方法来使用正则表达式验证,jQuery验证器的附加方法.js有一个名为pattern的规则可用于此目的
var lettersNumbersOnlyMinMaxCharactersRegex = /^[a-z0-9]{8,32}$/ig;
var validator = $("form").validate({
rules: {
ExampleInput: {
pattern: lettersNumbersOnlyMinMaxCharactersRegex
}
},
messages: {
ExampleInput: {
lettersNumbersOnlyMinMaxCharacters: "You must enter between 8 and 32 numbers and letters."
}
}
});
演示:Fiddle