Skip to content Skip to sidebar Skip to footer

Validating Broken Up Date Width JQuery Validation Plugin

jQuery Validation plugin is used to validate all form data: http://docs.jquery.com/Plugins/Validation Have 3 select fields for birth date: day, month, year. First: How i can make s

Solution 1:

You can add custom methods using $.validator.addMethod

Add two methods: one for checking for all 3 selections (FullDate) and one for checking age (Age). Since the 3 elements are grouped, I just put one method on one selector and the other on another selector.

Also, your errorPlacement function has an if/else that does the exact same thing, which isn't necessary.

$(function() {
  // this function requires month day and year selections
  $.validator.addMethod("FullDate", function() {
    //if all values are selected
    if($("#DOBd").val() != "" && $("#DOBm").val() != "" && $("#DOBy").val() != "") {
      return true;
    } else {
      return false;
    }
  }, '<img src="/path/to/image.png" alt="Please select a day, month, and year" title="Please select a day, month, and year" />');

  // this function checks the selected date, returning true if older than 18 years
  $.validator.addMethod("Age", function() {
    //only compare date if all items have a value
    if($("#DOBd").val() != "" && $("#DOBm").val() != "" && $("#DOBy").val() != "") {
      //get selected date
      var DOB = new Date($("#DOBy").val(), $("#DOBm").val(), $("#DOBd").val());
      var eday = new Date(); //get today
      eday.setFullYear(eday.getFullYear() - 18); //set to eighteen years ago
      //if older than 18
      if(DOB < eday) {
        return true;
      } else {
        return false;
      }
    }
    return true;
  }, '<img src="/path/to/image.png" alt="Must be 18" title="Must be 18" />');

  $("form").validate({
    rules: {
      DOBd: "FullDate",
      DOBm: "Age"
    },
    groups:{
      date_of_birth:"DOBd DOBm DOBy"
    },
    errorPlacement:function(error,element){
      error.appendTo(element.parent("td").next("td"));
    }
  });    
});

Post a Comment for "Validating Broken Up Date Width JQuery Validation Plugin"