JQuery Check multiple fields with one error

How can I use the jQuery Validate plugin to have one error message for three fields. For example, 3 dob fields. By default, I get 3 error messages if all 3 fields remain empty. I need only one error related to 3 fields. If any error occurs, an error occurs.

+55
jquery jquery-validate
Aug 17 '09 at 16:44
source share
7 answers

Like Chris

$("form").validate({ rules: { DayOfBirth: { required: true }, MonthOfBirth: { required: true }, YearOfBirth: { required: true } }, groups: { DateofBirth: "DayOfBirth MonthOfBirth YearOfBirth" }, errorPlacement: function(error, element) { if (element.attr("name") == "DayOfBirth" || element.attr("name") == "MonthOfBirth" || element.attr("name") == "YearOfBirth") error.insertAfter("#YearOfBirth"); else error.insertAfter(element); } }); 
+54
Dec 23 '10 at 3:19
source share

You can use a group to group inputs. If each of the inputs has an error message, only one will be displayed.

You will probably want to redefine the messages associated with each field, so they will make more sense. For example, by default, you may receive an error message like "This field is required." Well, this does not make the user much good when there are three inputs. You probably want to redefine the message to say "Local number required." In this example, I simply flipped all the error messages using "Please enter a valid phone number."

 <input type="text" name="countryCode" /> <input type="text" name="areaCode" /> <input type="text" name="localNumber" /> groups: { phoneNumber: "countryCode areaCode localNumber" }, rules: { 'countryCode': { required: true, minlength:3, maxlength:3, number:true }, 'contactInformation[areaCode]': { required: true, minlength:3, maxlength:3, number:true }, 'contactInformation[localNumber]': { required: true, minlength:4, maxlength:4, number:true }, }, messages: { "countryCode": { required: "Please enter a valid Phone Number", minlength: "Please enter a valid Phone Number", maxlength: "Please enter a valid Phone Number", number: "Please enter a valid Phone Number" }, "areaCode": { required: "Please enter a valid Phone Number", minlength: "Please enter a valid Phone Number", maxlength: "Please enter a valid Phone Number", number: "Please enter a valid Phone Number" }, "localNumber": { required: "Please enter a valid Phone Number", minlength: "Please enter a valid Phone Number", maxlength: "Please enter a valid Phone Number", number: "Please enter a valid Phone Number" } }, 
+13
Mar 18
source share

I thought I should share this. Full code that worked for me.

HTML

 <div class="clearfix bl"> <label>Fecha de nacimiento</label> <select name="fechanacimdia" id="fechanacimdia"></select> <select name="fechanacimmes" id="fechanacimmes"></select> <select name="fechanacimano" id="fechanacimano"></select> </div> 

Js

 //hay que poblar selects de fecha dia = $('#fechanacimdia'); mes = $('#fechanacimmes'); ano = $('#fechanacimano'); dia.append('<option>Día</option>'); for(i=1;i<=31;i++) { dia.append('<option value="'+i+'">'+i+'</option>'); } meses = ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"] mes.append('<option>Mes</option>'); for(i=1;i<=12;i++) { mes.append('<option value="'+i+'">'+meses[i-1]+'</option>'); } d = new Date(); year = d.getFullYear(); maxage = 100; minage = 16; ano.append('<option>Año</option>'); for(i=year-minage;i>=year-maxage;i--) { ano.append('<option value="'+i+'">'+i+'</option>'); } //--------- validate ------------------------ $('#formulario').validate({ rules: { fechanacimdia: { required: true }, fechanacimmes: { required: true }, fechanacimano: { required: true, validdate: true } }, groups: { fechanacim: "fechanacimdia fechanacimmes fechanacimano" }, messages: { fechanacimdia: "Fecha de nacimiento no es válida.", fechanacimmes: "Fecha de nacimiento no es válida.", fechanacimano: "Fecha de nacimiento no es válida." }, }); //funcion auxiliar para validar fecha de nacimiento correcta jQuery.validator.addMethod("validdate", function(value, element) { var month = +$('#fechanacimmes').val() - 1; // Convert to numbers with "+" prefix var day = +$('#fechanacimdia').val(); var year = +$('#fechanacimano').val(); var date = new Date(year, month, day); // Use the proper constructor return date.getFullYear() == year && date.getMonth() == month && date.getDate() == day; }); 
+4
Sep 05 '11 at 17:26
source share

this is for the HTML part:

 <div> <p class="myLabel left">Date of birth:</p> <p class="mandatory left">*</p> <div class="left"> <p><input type="text" name="dobDay" class="required" /></p> <p><i>dd</i></p> </div> <div class="left"> <p><input type="text" name="dobMonth" class="required" /></p> <p><i>mm</i></p> </div> <div class="left"> <p><input type="text" name="dobYear" class="required" /></p> <p><i>yyyy</i></p> </div> <div class="clear"></div> <div class="myError"> <label for="dateOfBirth" class="error">Please enter a valid date.</label> </div> </div> 

This is the script i used:

 $(document).ready(function() { $("#myForm").validate({ groups: { dateOfBirth: "dobDay dobMonth dobYear" }, rules: { 'dobDay': { required: true, minlength:1, maxlength:2, range: [1, 31], number:true }, 'dobMonth': { required: true, minlength:1, maxlength:2, range: [1, 12], number:true }, 'dobYear': { required: true, minlength:4, maxlength:4, number:true }, }, }); }); 

all of the HTML can be customized. I used this complex layout because I needed to add this field to an existing form. But this is an example that works! Hope this helps anyone!

+3
May 26 '11 at 13:12
source share

I needed to modify the jQuery validator to check something with the validateable attribute on it, as well as with standard inputs. You can get the 1.9.0 modified version of the plugin here

Basically you import a new jquery validation mechanism and do something like this:

 <script> $.validator.addMethod( "groupnotnull", function(value, element) { return $("input[type='text']:filled",element).length!=0; }, function(regexp, element) { return "At least one input must be specified"; } ); </script> <div validateable="true" name="groupValidated" groupnotnull="true"> <input type="text" name="foo"/> <input type="text" name="blah"/> </div> 

The modifications required for the jQuery validator were to use .attr('name') instead of .name because .name only works with form fields. And change the key handlers, etc., to bind them to validateable children.

This is slightly more dynamic than groups, because it allows you to check the fields in relation to each other, and not as separate objects.

+2
Apr 10 2018-12-12T00:
source share

This code will display one common error if any of the required fields is empty.

 <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(document).ready(function(){ $("#myform").validate({ invalidHandler: function(form, validator) { var errors = validator.numberOfInvalids(); if (errors) { var message ='You missed ' + errors + ' fields.'; $("#messageBox").html(message); $("#messageBox").show(); } else { $("#messageBox").hide(); } }, showErrors: function(errorMap, errorList) { }, submitHandler: function() { alert("Submit!") } }) }); </script> </head> <body> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> <div id="messageBox"></div> <ul id="errorlist"></ul> <form id="myform" action="/loginurl" method="post"> <label>DOB1</label> <input name="dob1" class="required" /> <label>DOB2</label> <input name="dob2" class="required" /> <label>DOB3</label> <input name="dob3" class="required" /> <br/> <input type="submit" value="Submit"/> </form> </body> </html> 
+1
Aug 22 '10 at 7:09
source share

A couple of options: check errorContainer . You can make all errors completely separated by <div> . Or you can check the invalid block and just have the errorMessage.show() command.

0
Aug 17 '09 at 17:17
source share



All Articles