Reputation: 3630
I am using jquery validation plugin for my form controls. I am easily able to validation three individual controls with three different messages with proper validation for number, minlength, maxlength. I have controls like web reference, date of birth, postcode and other fields, that have more than one textbox. Below is the html for web reference,
<input name="txtRef1" runat="server" type="text" id="txtRef1" />
<span class="ForwardSlash">-</span>
<input runat="server" name="txtRef2" type="text" id="txtRef2" />
<span class="ForwardSlash">-</span>
<input runat="server" name="txtRef3" type="text" id="txtRef3" />
I have written a custom validator method for this, which checks, if any of the above three textboxes are empty, then user will get one message - "Field is required". I don't want to have individual messages because it then breaks the design including forms design layout. The script to achieve the above is here:
function setuppagevalidationrecall() {
$.validator.addMethod('example',
function (value, element) {
return ((value != "") && ($('#txtRef2').val() != "") && ($('#txtRef3').val() != ""));
}, "Field is required");
var validator = $("#form1").validate({
rules: {
txtRef1: {
example: true,
number: true,
minlength: 3,
maxlength: 3
}
}
});
How can I improve this functionality to also check for number, minlength and maxlength so that for all the three textboxes above I get only one message as a validation message. And also to make the example method dynamic like with arguments so that it can be applied for any field like postcodes (2 textboxes), date of birth (3 textboxes, dd/mm/yyyy)
Upvotes: 1
Views: 2083
Reputation: 6086
Displaying a single validation message for multiple controls is what groups are for.
Specify grouping of error messages. A group consists of an arbitrary group name as the key and a space separated list of element names as the value. Use errorPlacement to control where the group message is placed.
use
groups:{ txtRef : "txtRef1 txtRef2 txtRef3" }
and
errorPlacement: function (error, element) {
if (element.attr("name") == "txtRef1"
|| element.attr("name") == "txtRef2"
|| element.attr("name") == "txtRef3")
error.insertAfter("#txtRef3");
else
error.insertAfter(element);
},
Try it here:
Upvotes: 1
Reputation: 14187
What are you trying to do can be handled by using correctly the invalidHandler
and errorPlacement
from jquery.validate
there is no need to create a function
to store just one global error message for lots of elements in a form.
I know jquery.validate
sometimes can be annoying because of all the errors fired at the same time but I am sure this will help you.
Take a look at this example:
As you can see, there is no custom function or tricky thing to get things working as you want.
Hope this helps :-)
Upvotes: 0