chnet
chnet

Reputation: 2033

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>

Upvotes: 3

Views: 15821

Answers (2)

Phil
Phil

Reputation: 11175

I would suggest you use the submit() and not the click on the button as you can place preventDefault and return false in the function to stop the button from submitting.

So:

if(validation is false) { return false }

Also, there appears to be a few syntax errors. Try using firebug (Every browser but IE) and fix those before moving forward.

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76900

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

   });
  });

Upvotes: 3

Related Questions