views:

210

answers:

2

Hi,

I have a regex problem that I need some advice on. I am using a jquery plugin that validates input fields on a JSP. I am using the date validation. It all works fine but this field is not required and is not marked as required. When the user hits submit it shows a warning on the date input field since the empty string does not match the validation of a date. I need some way to say that nothing or a date is valid in a regex.

Here is the regex for the date; is there any way to put "or empty" into this also:

"date":{
           "regex":"/^[0-9]{1,2}\-\[0-9]{1,2}\-\[0-9]{4}$/",
           "alertText":"* Invalid date, must be in MM-DD-YYYY format"},

Thanks in advance

A: 

(^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$|^$)

ennuikiller
Thanks for the fast reply. When I try that it doesn't do the validation at all and firebug shows me syntax error (^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$|^$)
Caroline
This is a standard regex "alteration" syntax (a|b) means match a or b. so not sure why you are getting a syntax error.
ennuikiller
me either, I had tried a few options like that already and I was getting the same issue. I suspect the jquery plugin is funny in terms of what it expects, possibly doesn't like the "or" at all. Thanks for helping though!
Caroline
This failed because the first caret interprets `^[0-9]` to "anything but 0-9"; the `|^$)` was probably not understood as well. In all honesty, I'd never write an optional group like this because a simple question mark after the group makes it optional. (IE, the way my answer's regex was written.)
The Wicked Flea
A: 

Try:

/^([0-9]{1,2}\-\[0-9]{1,2}\-\[0-9]{4})?$/

It will then match when a valid date is supplied, or the field is left blank.

The Wicked Flea
That worked, thanks a million!
Caroline
You're welcome, I'm happy to help. :)
The Wicked Flea