用Jquery进行时间验证 [英] Time Validation with Jquery

查看:73
本文介绍了用Jquery进行时间验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jquery验证插件来验证我的表单.要验证文本输入,我要做的就是在属性中写入class="required",它会对我进行验证.

I am using jquery validation plugin to validate my forms. To validate a text input all I do is write class="required" in the attribute and it does the validation for me.

现在,我正在尝试验证用户必须输入时间的输入(例如02:45:00 AM),但是我使用的插件没有任何用于时间验证的功能.因此,我必须为此构建自定义验证,但问题是我不了解Jquery:(

Now I am trying to validate an input where users will have to enter time( like 02:45:00 AM) but the plugin that I am using doesn't have any function for time validation. So, I have to build a custom validation for that but the problem is I have no knowledge of Jquery :(

能否请您告诉我该怎么做?

Could you please show me how to do this?

预先感谢

为您提供信息,我需要将其构建为12个小时的时间格式

For your information I need to build it for 12 hr time format

推荐答案

您可以使用jQuery验证程序addMethod().

You could use jQuery Validators addMethod().

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery.Validate/1.6/jQuery.Validate.js" type="text/javascript"></script>
<script type="text/javascript">

$().ready(function() {

$.validator.addMethod("time", function(value, element) {  
return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);  
}, "Please enter a valid time.");

    $("#login").validate({
            rules: {
                    time: "required time",
            },

     });

 });

 </script>
</head>
<body>
  <form id="login" name="login" method="post" action="#">
  <h1>Time Validation</h1><br />
  <label for="time">Enter Time</label>
  <input id="time" name="time" type="text" value="" tabindex="1" /><br />
  <input id="submit" name="submit" type="submit" value="Submit" tabindex="2" />
</form>
</body>
</html>​

这是一个jsfiddle- http://jsfiddle.net/e2DzT/

Here is a jsfiddle - http://jsfiddle.net/e2DzT/

我希望这会有所帮助.

这篇关于用Jquery进行时间验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆