I have tried to make a client side date validation using reg exp, but it do not work.
The format is in ddmmyyyy and ddmmyy and should accept both "-" and "."
function checkEmail(myForm) {
if (!/(\d{2}\-\d{2}\-\d{2,4}/).test(myForm.dato.value)) {
alert("Dato-feltet skal udfyldes korrekt!");
return(false);
}
else {
return(true);
}
}
.....
<FORM ACTION="action.php" METHOD="post" ENCTYPE="multipart/form-data" onSubmit="return checkEmail(this)">
<INPUT TYPE="text" NAME="date" SIZE="10" MAXLENGTH="10">
</FORM>
What goes wrong?
Thanks!
Ole
adios
10-06-2002, 02:13 AM
Your regex needed some work, allowing for alternative separators, checking for the right number of digits ({2,4} allows 2, 3 , or 4), losing the unnecessary parentheses/backslashes. Even so, if you think about it, there's a lot more that can be done to validate here, including checking that the date itself is a valid one. Adapted from Karen Gayda, see if this helps:
<html>
<head>
<title>untitled</title>
<script type="text/javascript" language="javascript">
function validateUSDate(field) {
var v = field.value, objRegExp = /^\d{2}(-|\.)\d{1,2}\1(\d{2}|\d{4})$/;
var msg1 = 'Please enter a date in one of these formats:';
msg1 += '\n\n\tdd-mm-yyyy\n\tdd.mm.yyyy\n\tdd-mm-yy\n\tdd.mm.yy';
msg2 = 'Invalid date. Please correct.';
if (!objRegExp.test(v)) {
alert(msg1);
field.focus();
field.select();
return false;
} else {
var strSeparator = v.substring(2,3);
var arrayDate = v.split(strSeparator);
var arrayLookup = {
'01': 31 , '03': 31 , '04': 30 , '05': 31 , '06': 30 , '07': 31 ,
'08': 31 , '09': 30 , '10': 31 , '11': 30 , '12': 31
};
var intDay = parseInt(arrayDate[0]);
if (arrayLookup[arrayDate[1]]) {
if (intDay <= arrayLookup[arrayDate[1]] && intDay != 0) return true;
}
if (arrayDate[1] == '02') {
var intYear = parseInt(arrayDate[2]);
if (((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28))
&& intDay !=0)
return true;
}
}
alert(msg2);
field.focus();
field.select();
return false;
}
function checkForm(f) {
if (!validateUSDate(f.date)) return false;
/* other validators here */
return true;
}
</script>
</head>
<body>
<b>The format is in ddmmyyyy and ddmmyy and should accept both "-" and "."</b><br>
<form action="javascript:alert('OK')" method="post" enctype="multipart/form-data"
onsubmit="return checkForm(this)">
<input type="text" name="date" size="10" maxlength="10">
<input type="submit">
</form>
</body>
</html>
http://www.rgagnon.com/jsdetails/js-0063.html
whammy
10-06-2002, 04:55 AM
Her work was what truly introduced me to regular expressions. If she has a paypal account I might even stick a few bucks in there. :D
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.