Reputation: 5920
I'm using the jQuery Validate Plugin to validate forms on my website. I would like to change the default minlength
message to show the number of characters STILL NEEDED in the field, and for this number to change as the user types in the input
field.
For example, if the minlength
rule is 15 characters, and there are 2 characters in the field, the error message would read "Please enter at least 13 more characters."
For the sake of simplicity, here's my jQuery. All of the code below does not function as desired when put together, so I need a solution that DOES work
Here's the fiddle: http://jsfiddle.net/ac2T2/1/
Here's my code:
$('#contactForm').validate({
rules: {
contactName: {
minlength: 15
}
}
});
I would like to add some code that does something like the following:
var numOfCharactersToGo = 15 - parseInt($('contactName').val().length);
and then in theory I could change my default jQuery message for minlength
as shown here:
jQuery.extend(jQuery.validator.messages, {
minlength: jQuery.validator.format('Please enter at least ' + numOfCharactersToGo + ' more characters.')
});
Upvotes: 1
Views: 7141
Reputation: 5920
Thanks to @Sparky's answer leading me in the right direction, here's the final answer in case anyone else wants the same functionality.
Here's the fiddle: http://jsfiddle.net/ZhRGA/8/
HTML
<form id="myform">
<input type="text" name="field1" id="field1" />
<br/>
<input type="submit" />
</form>
jQuery
$(document).ready(function () {
var minChar = 15;
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
minlength: minChar
}
},
messages: {
field1: {
minlength: function () {
return [
(minChar - parseInt($('#field1').val().length)) +
' more characters to go.'];
}
}
}
});
});
Upvotes: 2
Reputation: 98748
You cannot dynamically change rules
or messages
after the plugin has been initialized on the form, without using a built-in method for such changes.
There's only one way that I know about where you can dynamically over-ride any rules and messages after initialization. That's with the rules('add')
method.
$('#field').on('keyup', function () {
current = 15 - parseInt($(this).val().length);
$(this).rules('add', {
minlength: 15,
messages: {
minlength: current + " characters to go"
}
});
});
You'd need to call the above inside your keyup
event handler function or whatever function you're using to dynamically count the characters. The demo is crude and has some issues to overcome, but it shows that it might be possible.
Very Crude DEMO: http://jsfiddle.net/ZhRGA/5/
Upvotes: 1