Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery validation date

How can I validate date format before I submit the form? I tried to do the following. However, it does not work.

  <p> Date: <br />
  <input type="text" id="date" name="date">
  </p>

<input type="submit" id="submit" value="Send" />

</fieldset>


</form>

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>

<script>
 $(function() {

    $('#submit').click(function() {
     $.validator.addMethod(
     "DateFormat",
     function(value, element) {
     return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
     },
      "Please enter a date in the format dd/mm/yyyy";
     );

      // validate and process form here
     $('#contact').validate({
        rules :
        date: {
        DateFormat : true
       }
     });

      var dataString = $('form[name="contact"]').serialize();

      $.ajax({
       type: "POST",
       data: dataString,
       url : "ajax.php",
     });

   });
  });

</script>
like image 203
chnet Avatar asked Mar 08 '26 14:03

chnet


1 Answers

You should load jquery before the plugin like this:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>

Otherwise the validation plugin won't work.

EDIT - you had some errors in your javascript code, here is a working fiddle http://jsfiddle.net/Eu8eS/1/

working code:

$(function() {

    $('#submit').click(function() {
     $.validator.addMethod(
     "DateFormat",
     function(value, element) {
     return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
     },
      "Please enter a date in the format dd/mm/yyyy"//removed ;
     );

      // validate and process form here
     $('#contact').validate({
         rules :{//added here {
        date: {
        DateFormat : true
         }
       }//added here }
     });

      var dataString = $('form[name="contact"]').serialize();

      $.ajax({
       type: "POST",
       data: dataString,
       url : "ajax.php",
     });

   });
  });
like image 154
Nicola Peluchetti Avatar answered Mar 11 '26 06:03

Nicola Peluchetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!