Reputation: 14159
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.substr(i,1);
if (currentChar == '/' && (i != 5 || i != 8))
{
alert("Invalid date format");
document.getElementById('LDate').focus;
status = false;
}
if (status == false)
break;
}
}
Upvotes: 0
Views: 220
Reputation: 14159
Chris,
Thanks for the suggestion of using widgets.
I tried the OpenJS library and it is working absolutely fine:
Upvotes: 0
Reputation: 55447
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;
}
Upvotes: 1
Reputation: 4305
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;
}
Upvotes: 2
Reputation: 4067
I think you'll need to write such a function yourself.
The validation could be done using regular expressions:
~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?
Upvotes: 0