繁体   English   中英

在javascript中验证DD-MM-YYYY格式

[英]Validating DD-MM-YYYY formation in javascript

下面是我的 javascript,首先是我的 xhtml 代码,我试图让它验证我的日期,但是它选择了我输入的每个日期作为无效日期,有人可以告诉我缺少什么任何帮助会提前谢谢

function validateForm(form)
{
    var a, i, title, fname, lname, sex, address, email, username, password, confirm, error, check, type, contact, date;
    var reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);

    a=0;
    check=false;
    error=false;

    //other codes
    date=document.getElementById('date').value;
    //other code

if (matches == null) 
    alert('Please enter a valid date of birth');
    return false;
    var d = matches[2];
    var m = matches[1] - 1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;

下面是我的 html

    <form name="myForm" method="post" action="sub.html" onsubmit="return validateForm();">
    <fieldset>

    <p>Last Name:<input id="lastname" type="text" name="lname" size="40" placeholder="Last Name"/>*</p>

    <p>Sex: &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Male <input id="mletter" type="radio" name="sex" value="male"/> &nbsp; &nbsp; Female <input id="fletter" type="radio" name="sex" value="female"/>*</p>

    <p>Date Of Birth: <input id="date" type="text" name="dob" placeholder="MM-DD-YYYY"/>*</p>

    <p>Address: &nbsp; &nbsp; <textarea id="address" rows="4"  cols="40" ></textarea>*</p>


    </fieldset>
    </form>

在获取date值之前,您正在检查格式

此外, if可能需要一些大括号来包含return false

var matches, date;
//other codes
date=document.getElementById('date').value;
matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if(matches === null){
    alert('wrong date format');
    return false;
}

要检查无效的日期字符串格式,首先获取要检查的日期字符串

date=document.getElementById('date').value;

然后用regexp做一个exec

matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);

不要以相反的顺序进行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM