JQuery Validate multiple fields with one error

Solution 1:

Similar to Chris's

$("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);
   }
});

Solution 2:

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

You'll probably want to override the messages associated with each of the fields, so they'll make more sense. For example, by default, you might get an error message like, "This Field is required." Well, that doesn't do the user alot of good when there are three inputs. You probably want to override the message to say "The Local Number is required." For this example, I just overrode all the error messages with "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"
  }
},

Solution 3:

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 the HTML part can be customize as you see fit. I used these complex layout because I needed to add this field to an already existing form. But it is an example that works! Hope it helps anyone!

Solution 4:

I thought I should share this. The 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;
});

Solution 5:

My take on it was to change jQuery validator to validate anything with the validateable attribute on it as well as the standard inputs. You can get the 1.9.0 modified version of the plugin here

Basically you import the new jquery validator 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 on jQuery validator were to make it use .attr('name') instead of .name because .name only works on form fields. And modify the key up handlers etc. to bind to children of the validateable element.

This is a little more dynamic than groups in that it allows fields to be validated in relation to each other rather than just as single entities.