Link to home
Start Free TrialLog in
Avatar of Obadiah Christopher
Obadiah ChristopherFlag for India

asked on

Regex for Date onkeypress

Is it possible to write a regular expression to Validate a date in the onkeypress event of a textbox?

The user should be able to enter dates in the following formats.

1. MM/dd/yyyy - 12/25/2011
2. MMMM dd, yyyy - December 25, 2011
3. dd MMM,yyyy - 25 Dec,2011

I have a dropdown in which the user will select the format of the date to be entered, so I would require 3 different Regex.

I can write a regex on blur event. But is it possible to write it in keypress event of textbox.
Avatar of Bardobrave
Bardobrave
Flag of Spain image

The problem of using keypress event is that your regex comparison will be fired with each key pressing, so it will never pass until the last character is pressed (and thus it will return warning, error, or whatever are you using to alert your user of it each time).

Maybe you can launch it on keypress but only check for conformance with the regular expression when the correct number of characters are inserted.
Avatar of Obadiah Christopher

ASKER

Exactly. But is it possible to prevent the user frm entering any other characters other than valid ones.
Of course you can, but not matching against a full regular expression (as in each keypress you'll only have a bit of the date builded).

You can use different reg exps for the different steps in the creation or use code to validate each keypress depending on what format you expect.

The problem in this is... what if your user copy/paste the date into your textbox? You should maintain the onBlur validation.
Onblur validation is already present. But they want keypress also. I'm doing all these validations in onBlur event. The problem is for keypress event.
You can do a function for keypress event.

When if fired, this function check if the current value of the textField matches with the expected format for a string of it's length.

If the pressed key don't match, you can erase the last char from the textbox. This maybe don't work very well when users types fast, as maybe your function finishes it's execution after the next key is pressed, so the erasing of the last char will have a delay.

Probably will be better to simply show a message alerting user that introduced date doesn't match with the expected format instead of trying to block the pressing of erroneus keys.
The regular expression is the thing that I'm looking for. Can somebody help me with writing this Regular Expression.
ASKER CERTIFIED SOLUTION
Avatar of Bardobrave
Bardobrave
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Accepting the answer for the regex. However, I assume that it is not possible to do it on keypress.