如何使用jQuery验证字符串是否为日期 [英] how to validate if string is date with jquery
本文介绍了如何使用jQuery验证字符串是否为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何解析字符串是否为有效日期.我尝试了网络上的所有内容,但没有任何效果.我知道这个问题以前曾被问过多次,但是即使在说他们已解决问题的线程中,对我也不起作用.我开始问自己有没有办法. 我将在这里发送我的代码.我有三个文本框:一个用于日,一个用于月和年,以及在提交表单时,我需要检查它们是否形成有效日期.
How to parse if string is valid date. I tried everything in the web, and nothing works. I know that the question is asked multiple times before, but even in the threads that say they solved the problem, does,not work for me. I start to asking myself is there a way at all. I will send my code here. I have three text box: one for day, one for month and year, and on form submit I need to check if they form valid date.
<html>
<head>
<title>Simple Form Validation</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.addMethod(
"customDateValidator",
function(value, element) {
var concateDate;
concateDate= $("#day").val() + "/" + $("#month").val() + "/" + $("#year").val();
var rslt= (Date.parseExact(concateDate, "d/M/yyyy") );
if(isNaN(rslt))
return false;
else
return true;
},
"Please enter a valid date"
);
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#form1").validate({
rules: {
year: {
customDateValidator: true
}
},
messages: {
year: "Please enter valid datum."
}
});
});
</script>
</head>
<body>
<form id="form1" method="post" action="">
<div class="form-row"><span class="label">Day *</span><input type="text" name="day" id="day" /></div>
<div class="form-row"><span class="label">Month *</span><input type="text" name="month" id="month" /></div>
<div class="form-row"><span class="label">Year</span><input type="text" name="year" id="year" /></div>
<div class="form-row"><input class="submit" type="submit" value="Submit"></div>
</form>
</body>
</html>
推荐答案
这就是我的做法,并且效果很好.
This is how I'm doing it and it works well.
rules: {
month: { required: true },
day: { required: true },
year: { required: true, date_check: function(){ return $("#month").val()+'/'+$("#day").val()+'/'+$("#year").val() } }
}
jQuery.validator.addMethod("date_check",function(a,b,c){
month = c.substring(0,2)-1;
day = c.substring(3,5);
year = c.substring(6,10);
mSeconds = (new Date(year, month, day)).getTime();
objDate = new Date();
objDate.setTime(mSeconds);
if(objDate.getFullYear() != year || objDate.getMonth() != month || objDate.getDate() != day) {
return false;
}
return true;
}, "Please provide a valid date.");
这篇关于如何使用jQuery验证字符串是否为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文