如果字符串是有效日期,如何解析。我在网上尝试了一切,没有任何作用。我知道这个问题之前已被多次询问过,但即使在说他们解决问题的线程中,也不会对我有用。我开始问自己是否有办法。 我会在这里发送我的代码。我有三个文本框:一个用于一天,一个用于月份和一年,在表单提交时我需要检查它们是否构成有效日期。
<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>
答案 0 :(得分:4)
这就是我正在做的事情并且运作良好。
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.");