/    Sign up×
Community /Pin to ProfileBookmark

How to do this

Hello All,

I am back with a new problem.Now i have one textbox and what i want to enter a date in that textbox in the mm/dd/yyyy format.If the date is in the wrong format like mm have get value 13 or greater than 13 then a messagebox must have to appear showing a perticular message.The same thing must have to happen with dd anf yyyy fields also.Can it be possible on the keypress event if it is then please send me the proper code in Javascript .

Thanks & Regards

Prashant S. More

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@DokOct 21.2008 — Show us the code you have so far.
Copy linkTweet thisAlerts:
@mrhooOct 21.2008 — The best solution is to give your users a calendar or datepicker control that only allows them to select valid dates.

But if you insist on text input, here are a couple tips-

'2/29/2008' is a 'real' date, and '2/29/2009' is not, but you don't know that until the last digit.

You can use Date.parse or split the string into its parts to create a date from the input.

Remember that parsing '2/29/2009' [B]does [/B]make a valid date. (March 1rst).

An input of'60/60/2000' may be converted to'Jan 29 2005'.

Compare all the parts of the resulting Date with the original input.

But it is a much better tactic to let the users pick from valid choices than to have to teach them how you prefer to format a date string.


These two methods return a new Date object or false from their argument.

Use dmy for dd/mm/yyyy, and mdy for mm/dd/yyyy

[CODE]Validate={
dmy: function(str, monthfirst){
var A= str.split(/D+/);
try{
A= monthfirst? [A[2]*1, A[0]-1, A[1]*1]: [A[2]*1, A[1]-1, A[0]*1];
var D= new Date(A[0], A[1], A[2]);
if(D.getFullYear() == A[0] && D.getMonth()== A[1] && D.getDate()== A[2]){
return D;
}
}
catch(er){
}
return false;
},
mdy: function(str){
return Validate.dmy(str, true);
}
}[/CODE]

//test

alert(Validate.dmy('29/2/2009'));

alert(Validate.mdy('2/29/2009'));

alert(Validate.dmy('29/2/2008'));

alert(Validate.mdy('2/29/2008'));
×

Success!

Help @Prashmo spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...