使用 Jquery 进行时间验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7294131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:39:28  来源:igfitidea点击:

Time Validation with Jquery

jquery

提问by black_belt

I am using jquery validation pluginto 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.

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

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 :(

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

Could you please show me how to do this?

你能告诉我怎么做吗?

Thanks in advance

提前致谢

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

为了您的信息,我需要为 12 小时时间格式构建它

回答by martyhines

You could use jQuery Validators addMethod().

您可以使用 jQuery 验证器 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>?

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

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

I hope this helps.

我希望这有帮助。