下面是我的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: Male <input id="mletter" type="radio" name="sex" value="male"/> 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: <textarea id="address" rows="4" cols="40" ></textarea>*</p>
</fieldset>
</form>
答案 0 :(得分:2)
在获取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;
然后使用exec
regexp
matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
不要按相反的顺序进行。