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 selectedif($("#DOBd").val() != "" && $("#DOBm").val() != "" && $("#DOBy").val() != "") {
      returntrue;
    } else {
      returnfalse;
    }
  }, '<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 valueif($("#DOBd").val() != "" && $("#DOBm").val() != "" && $("#DOBy").val() != "") {
      //get selected datevarDOB = newDate($("#DOBy").val(), $("#DOBm").val(), $("#DOBd").val());
      var eday = newDate(); //get today
      eday.setFullYear(eday.getFullYear() - 18); //set to eighteen years ago//if older than 18if(DOB < eday) {
        returntrue;
      } else {
        returnfalse;
      }
    }
    returntrue;
  }, '<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"