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

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

问题描述

我最近开始研究 Javascript.我正在测试的是检查有效格式的 DoB.下一步将检查年龄.

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.

我的 HTML 代码包含的内容如下

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>
.
.

我在我的 .js 文件中做了以下事情

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
";
        return false;
    }
    else {
        return true
    }
}

我试图用正则表达式检查它是否有效,但即使我正确输入了日期,我也总是收到警报.以及如何分开 DD/MM/YYYY 来计算年龄?

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天全站免登陆