Javascript日期验证(DD / MM / YYYY)&年龄检查 [英] Javascript Date Validation ( DD/MM/YYYY) & Age Checking

查看:149
本文介绍了Javascript日期验证(DD / MM / YYYY)&年龄检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用Javascript。我正在测试的是以有效格式检查DoB。下一步将检查年龄。



我的HTML代码包含以下内容:

 <表单名称=返回checkForm();> =多个/表格数据目标=_自我onsubmit =返回checkForm();> =ProcessInfoaction =#method =POSTenctype = 




< br>
< label for =txtDOB>出生日期:*< / label>
< input id =txtDOBtype =textname =txtDOBsize =12>
格式:## / ## / ####
< br>



< / form>


我在.js文件中做了以下操作:

  var errMessage =; 

函数checkForm(){
validateName();
validateSurname();
carSelect();
validateDOB();

if(errMessage ==){
} else {
alert(errMessage);





函数validateDOB()
{
var dob = document.forms [ 。ProcessInfo ] [ txtDOB]值;
var pattern = / ^([0-9] {2}) - ([0-9] {2}) - ([0-9] {4})$ /
if(dob == null || dob ==||!pattern.test(dob)){
errMessage + =出生日期无效\\\
;
返回false;
}
else {
return true
}
}

我试图检查它是否对正则表达式有效,但即使正确输入日期,我也总是会收到警报。我怎么能分开DD / MM / YYYY来计算年龄?

解决方案

如果你想使用正斜杠格式,你需要在正则表达式中用反斜线转义:

  var pattern = / ^([0-9] { 2})\ /([0-9] {2})\ /([0-9] {4})$ /; 

http:// jsfiddle.net/P9TER/


I've started to work on Javascript recently. What I am testing is checking the DoB in valid format. Next step will be checking the age.

What my HTML code includes is below

<form name="ProcessInfo" action="#" method="POST" enctype="multipart/form-data" target="_self" onsubmit="return checkForm();">
.
.
.
.
<br>
<label for="txtDOB">Date of Birth:* </label>
<input id="txtDOB" type="text" name="txtDOB" size="12">
format: ##/##/####
<br>
.
.
.
</form>
.
.

and I did the following in my .js file

var errMessage = "";

function checkForm() {
    validateName();
    validateSurname();
    carSelect();
    validateDOB();

    if (errMessage == "") {
    } else {
        alert(errMessage);
    }
}

...

function validateDOB()
{
    var dob = document.forms["ProcessInfo"]["txtDOB"].value;
    var pattern = /^([0-9]{2})-([0-9]{2})-([0-9]{4})$/;
    if (dob == null || dob == "" || !pattern.test(dob)) {
        errMessage += "Invalid date of birth\n";
        return false;
    }
    else {
        return true
    }
}

I tried to check if its valid with regular expression but I always get an alert even if I type the date correctly. And how can I seperate the DD / MM / YYYY to calculate the age?

解决方案

If you want to use forward slashes in the format, the you need to escape with back slashes in the regex:

var pattern =/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/;

http://jsfiddle.net/P9TER/

这篇关于Javascript日期验证(DD / MM / YYYY)&amp;年龄检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆