开发者

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开发者_StackOverflow社区\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>


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

   });
  });


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜