Forum Moderators: open
it seems my users are used to entering dates in a different format...
how can i validate this field so that if they enter the wrong date format, it gives them an alert to fix it...
or better yet, is there a way to see the format they entered, and automatically fix it for them? (i know thats asking alot)
thanks all..
The HTML.....
<input name='date' type='text'>
<input name='realdate' type='hidden'>
ok, we've got a text field for the date, and a hidden field for the changed around version.
The script......
var userdate = document.form.date.value;
var mydate = userdate.replace( /(\d+)\D(\d+)\D(\d+)/, "$3-$1-$2");
alert( mydate);
document.form.realdate.value = mydate;
Basically, the regular expression matches:
Some numbers: \d+
A single non-number character: \D
Some numbers: \d+
A single non-number character: \D
Some numbers: \d+
By putting the \d+'s in ()'s, we capture their matches into $1, $2 and $3 in the order they appear. Then in the replacement string we simply swap them around with the hyphen in the middle.
You should note though, that if the user enteres nonsense, this won't fail, or produce an error. If no mm, dd, or yyyy is matched, the realdate field will simply contain "--", but I guess you already have incorrect date code somewhere.
Here's a shorter version that will replace the text, but beware, if the user realises you're changing it round, he may decide to be helpful and put it in how you want it. Then the script will muddle it up and you'll get the wrong format again. That's why it's better to use a hidden field.
Here's the shorter way......
var userdate = document.form.date.value;
var mydate = userdate.replace( /(\d+)\D(\d+)\D(\d+)/, "$3-$1-$2");
document.form.date.value = mydate;
See, we're putting the value back into the date field instead. If you really wanted to you could condense this into 1 line, but I like to break it down so it's more readable.