J. J. Cale wrote:
The
user can also input directly to the text inputs and I would like to route
whatever the user inputs through a filter using regexes wherever possible.
See if the following can help you into building your script (slightly
tested only). Note that proposing two ways to input data could confuse
the user (not mentioning different date formats across the world);
moreover you'll still have to validate the input server-side.
HTH
<form action="foo.pl" onsubmit="return validate(this)">
<input type="text" name="ctrlDate" title="dd/mm/yyyy">
<input type="submit">
</form>
<script type="text/javascript">
function padLeft(str, pad, count) {
while(str.length<count)
str=pad+str;
return str;
}
function isValidDate(y, m, d){
var da=new Date(y, m, d);
return da.getFullYear()==y &&
da.getMonth()==m &&
da.getDate()==d;
}
function check(el, field) {
//controller
var result={errors:[]}, r;
for(var ii=2; ii<arguments.length; ii++) {
r=singleCheck(el, field, arguments[ii]);
for(var j=0; j<r.errors.length; j++)
result.errors[result.errors.length]=r.errors[j];
}
return result;
//single check
function singleCheck(el, field, type) {
var result={errors:[]};
switch(type) {
case "date" :
var reDate, match, year, month, day;
reDate=
/^(\d{1,2})([-.,\/\\ ])(\d{1,2}|\w{3})(\2)(\d{1,2}|\d{4})$/i;
if((match=reDate.exec(el.value))) {
//store values
year=match[5];
month=match[3];
day=match[1];
//convert the month if needed
if(/\D/.test(month))
month={
jan:"1", feb:"2", mar:"3", apr:"4", may:"5", jun:"6",
jul:"7", aug:"8", sep:"9", oct:"10", nov:"11", dec:"12"
}[month.toLowerCase()]||"0";
if(+month<1 || +month>12)
result.errors[result.errors.length]=
"Field \""+field+"\" : month not recognised";
//convert the year if needed
if(year.length==1) year="0"+year;
if(year.length==2) year=((+year<=10) ? "20":"19") + year;
if(+year<1929 || +year>2010)
result.errors[result.errors.length]=
"Field \""+field+"\" : "+
"year should be between 1929 and 2010";
///validate the date
if(result.errors.length==0) {
if(!isValidDate(year, month-1, day)) {
result.errors[result.errors.length]=
"Field \""+field+"\" : invalid date found";
} else {
//format the input
el.value = padLeft(day,"0",2) + "\/" +
padLeft(month,"0",2) + "\/" +
year;
}
}
} else {
//format not correct
result.errors[result.errors.length]=
"Field \""+field+"\" : invalid format (try dd/mm/yyyy)";
}
break;
}
if(el.style)
el.style.borderColor = result.errors.length>0 ? "#c00" : "";
return result;
}
}
function validate(form){
var a=[], msg=[], index=1;
a[a.length]=check(form.elements["ctrlDate"], "date", "date");
for(var ii=0; ii<a.length; ii++)
if(a[ii].errors.length>0)
for(var j=0;j<a[ii].errors.length; j++)
msg[msg.length]=(index++)+" - "+a[ii].errors[j];
if(msg.length) alert(msg.join("\n"));
return false; //!msg.length;
}
</script>