Reputation: 770
I'm kind of puzzled at the results I'm getting from a Laravel date validation. The rule in question is:
'date_of_birth'=>array('required', 'date_format:n/j/Y')
What I'm finding is that if somebody enters 10/12/13, it passes validation, and gets stored as 10/12/0013. Obviously, that's not good. Is there any way of getting validation to demand a four-digit year? I assumed that's what the Y in the format would do.
Upvotes: 4
Views: 3379
Reputation: 15220
Posting my comment as an answer
Note: This is related to this question and the general discussion there. The workaround was posted in this answer on the above mentioned question. The PHP bug is mentioned in this comment. So I do not take any credit for this solution.
The Answer: This seems to be a bug in PHP's function date_parse_from_format(). You can work around it by specifying stricter rules with a regex expression:
array('required', 'date_format:n/j/Y', 'regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/')
It may look complicated at first if you're not familiar with regex, but if you break it apart, it's just says:
[0-9]{2}
= there must be 2 subsequent digits, each between 0 and 9.
[0-9]{4}
= there must be 4 subsequent digits, each between 0 and 9.
\/
= there must be a slash. It's escaped by the backslash.
BUT: Personally, I do not quite like this solution. Even though it ensures a four-digit year, a date like '99/99/9999' would still pass.
This is not the case with your after:01-01-1900
workaround. So, even though it's not being used as intended, I would still go with
'date_of_birth'=>array('required', 'date_format:"n/j/Y"', 'after:01-01-1900')
(or maybe adjust the regex a little...).
One thing to keep in mind: It works, but I'm not quite sure why. The underlying PHP function on the after-filter is DateTime::createFromFormat().
DateTime::createFromFormat('n/j/Y', '99/99/9999');
gives me a date of '10007-06-07', which should actually be after '01-01-1900', but the validator fails - maybe because of the comparison of the two dates, maybe because of the invalid values. And I have no idea how it was calculated. It's somewhat unpredictable behaviour, so handle with caution :)
If it's stupid but it works, it isn't stupid. - Murphy's law
Upvotes: 2