3

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>
3

2 Answers 2

3

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

   });
  });
2
  • you had errors in your code, check the fiddle and my corrections Jul 6, 2011 at 15:38
  • oops this wasn't here when I posted, :D
    – Phil
    Jul 6, 2011 at 15:40
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.