[英]Not able to Validate date in Javascript
I would need to validate my date. 我需要确认日期。 But when I key in 01132014 , it doesn't show any error message and it prints out 01 Jan, 2015 Also when I key in 06035555, it doesn't print out any error and continue to show 06 Mar 5555
但是,当我键入01132014时 ,它不显示任何错误消息并打印出2015年1月1日。同样,当我键入06035555时,它不显示任何错误并继续显示06 Mar 5555
But if I key in weird dates like 33333333, it does prints out "Your input has no logic at all" 但是,如果我输入的日期很奇怪,例如33333333,它会打印出“您的输入完全没有逻辑”
Additionally, I do not want the error message to pop up an alert box. 此外,我不希望错误消息弹出警报框。 I want the error message to be shown on the textbox itself.
我希望错误消息显示在文本框本身上。 How do I do it?
我该怎么做?
May I know what should I add in to validate? 我可以知道要添加什么以进行验证吗? I tried to view other answers but still, it's not working.
我尝试查看其他答案,但仍然无法正常工作。
Javascript: 使用Javascript:
function parseDate(s) {
if (isNaN(Date.parse(s))) {
alert("Your input has no logic at all");
return;
}
var reg = /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g;
var dateParts = s.split("/");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
var dateStrParts = date.toString().split(" ");
return (date.getDate() + ", " + dateStrParts[1] + " " + dateStrParts[3]);
}
</script>
Calendar Tag: 日历标签:
<p:calendar
value="#{pc_Rpt2202.asat_date}"
id="rp2202_input_as_at"
styleClass="calendar"
maxlength="10"
pattern="dd MMM yyyy"
onchange="$(this).val(parseDate($(this).val()))"
onfocus="$(this).mask('99/99/9999');"
>
<p:watermark for="rp2202_input_as_at" value="dd/MMM/yyyy" />
<f:convertDateTime pattern="dd MMM yyyy" />
</p:calendar>
Ok, two things. 好,两件事。 First, Date.parse tends to be implementation specific and so I wouldn't use it.
首先,Date.parse倾向于特定于实现,因此我不会使用它。 And second, basically regex is a pattern validator, not a content validator.
其次,正则表达式基本上是模式验证器,而不是内容验证器。 You best bet is to keep the regex simple, something like
/^(0?[1-9]|[12][0-9]|3[01])\\/(0[1-9]|1[0-2])\\/(19|20)[0-9][0-9]$/
and then afterwards split and check the content of the pieces, like so: 最好的选择是保持正则表达式简单,类似于
/^(0?[1-9]|[12][0-9]|3[01])\\/(0[1-9]|1[0-2])\\/(19|20)[0-9][0-9]$/
,然后拆分并检查片段的内容,如下所示:
var re = /^(0?[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[0-2])\/(19|20)[0-9][0-9]$/;
if (!re.test(s)) {
$('#rp2202_input_as_at').val("Your input has no logic at all");
return;
}
var dateParts...etc.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.