I have a regular expression rule setup for jQuery Validate. However, once the highlight method is fired, I can't seem to get the Unhighlight method to fire, no matter what I type in the field.
Here is a sample:
<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>
If I type 8 letters the regular expression should be matched and the error message should be cleared. But this isn't happening. I put a breakpoint in Google Chrome developer tools on the contents of the unhighlight method but it never seems to be hit.
onkeyupcallback function should not have a.valid()inside of it, and what is$('#ExampleInput')supposed to be? You should havethis.element(element)to trigger validation within this callback instead of.valid().