Verifying date format
I want to verify that the date entered is in yyyy/mm/dd format. If by mistake user enters in dd/mm/yyyy format, it must automatically convert to yyyy/mm/dd using Javascript function.
Edited:
function CheckDateFormat()
{
EnteredText = document.getElementById('LDate').value;
LengthOfText = EnteredText.length;
Status = true;
for(i=0;i<=LengthOfText;i++)
{
currentChar = EnteredText.sub开发者_如何学编程str(i,1);
if (currentChar == '/' && (i != 5 || i != 8))
{
alert("Invalid date format");
document.getElementById('LDate').focus;
status = false;
}
if (status == false)
break;
}
}
You can't autocorrect from dd/mm/yyyy or mm/dd/yyyy, since it's impossible to tell whether person meant dd/mm or mm/dd in dates such as 03/04/2009, for example.
So only thing you can do is cut the check with regexp:
function CheckDateFormat()
{
EnteredText = document.getElementById('LDate').value;
LengthOfText = EnteredText.length;
Status = true;
dformat= /^\d{4}\/\d{1,2}\/\d{1,2}$/
if (dformat.test(EnteredText) == null)
{
alert("Invalid date format");
document.getElementById('LDate').focus;
status = false;
}
if (status == false)
break;
}
If your constraints are that people will use YYYY/MM/DD or DD/MM/YYYY then you can use this. Like Gnudiff said, there's no way of handling MM/DD/YYYY alongside DD/MM/YYYY. I'd really recommend forcing a calendar widget on the person and not allow them to enter text if you think this might be a problem.
function vd(s) {
if (!s) {
//Do whatever you want for an error here
return null;
}
//YYYY/MM/DD
if (s.match(/^((19|20)\d{2})\/(0[1-9]|1[0-2])\/(0[1-9]|[1-2][0-9]|3[0-1])$/)) {
return s;
}
//DD/MM/YYYY
if (s.match(/^(0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d{2})$/)) {
var m = /^(0[1-9]|[1-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d{2})$/.exec(s);
return m[3] + '/' + m[2] + '/' + m[1];
}
//Second error here
return null;
}
I think you'll need to write such a function yourself.
The validation could be done using regular expressions:
- Check if the input is in the format you wish it'd be. If true, do whatever you have to.
- Check if the input is in format N and convert it to the format you wish it'd be.
- Repeat step 2 until you really don't know in which format the date could be.
- Display an error. (And don't forget to stop the submission and/or further processing of the input.)
~Chris
PS: Search on regexlib.com and google for some common date validation patterns. You don't want to invent the wheel again, do you?
Chris,
Thanks for the suggestion of using widgets.
I tried the OpenJS library and it is working absolutely fine:
精彩评论