日期格式MM/DD/YYYY的正则表达式返回错误结果 [英] Regular expression for date format MM/DD/YYYY returns false results
本文介绍了日期格式MM/DD/YYYY的正则表达式返回错误结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个jQuery日期选择器,每次单击文本框(prfm_dtrequest)时都会弹出.它返回mm/dd/yyyy格式,这是我想要的格式.之后,我需要验证文本框的内容,以确保其格式正确,然后单击提交"按钮(#submitform)将其加载到数据库中.即使我
I have a jquery date picker that pops up everytime I click my textbox(prfm_dtrequest). It returns mm/dd/yyyy format which is the way I want it to be. I need to validate the content of the textbox afterwards to make sure it is in the correct format before loading it into my database when clicking the submit button(#submitform). My code below only returns "is not a valid date" even if I
<!DOCTYPE html>
<html lang="en">
<head>
<title>testing</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#prfm_dtrequest" ).datepicker();
});
</script>
<script>
$(document).ready(function(){
$("#submitform").click(function(){
var daterequested = $("#prfm_dtrequest").val();
var dateMMDDYYYRegex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;
if(dateMMDDYYYRegex.test(dateMMDDYYYRegex)){
alert('is a valid date: '+daterequested);
}else{
alert('is not a valid date: '+daterequested);
}
});
});
</script>
</head>
<meta charset="utf-8">
<body>
<form method='post' action=''>
<input type="date" id="prfm_dtrequest" class='txtfld01' name=''><input type="submit" id="submitform" value="submit">
</form>
</body>
</html>
推荐答案
请更正您的正则表达式(有效日期示例: 03/31/1988 ):
Please correct your regex (valid date example: 03/31/1988):
$(document).ready(function(){
$("#submitform").click(function(){
/* isValidData source: http://stackoverflow.com/questions/5812220/how-to-validate-a-date */
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[0] - 1, bits[1]);
return d && (d.getMonth() + 1) == bits[0] && d.getDate() == Number(bits[1]);
}
var daterequested = $("#prfm_dtrequest").val();
var dateMMDDYYYRegex = "^[0-9]{2}/[0-9]{2}/[0-9]{4}$";
if(daterequested.match(dateMMDDYYYRegex) && isValidDate(daterequested)){
alert('is a valid date: '+daterequested);
}else{
alert('is not a valid date: '+daterequested);
}
});
});
结果:
这篇关于日期格式MM/DD/YYYY的正则表达式返回错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文