Reputation: 9986
i have this function:
var isValidDate = function (date) {
var regEx = /^\d{2}\\d{2}\\d{4}$/;
return date.match(regEx) !== null;
};
I want to validate my date with this form :
23/01/2015
My question is my REGEX it is good ..?
Upvotes: 0
Views: 399
Reputation: 3299
You may use html5 pattern .
better pattern ^([0-2]\d|3[0-1])\\(0\d|1[0-2])\\[1-2]\d{3}$
. it will also work in regex..
<input type="text" pattern="^\d{2}\\\d{2}\\\d{4}$" /><br/>
better
<input type="text" pattern="^([0-2]\d|3[0-1])\\(0\d|1[0-2])\\[1-2]\d{3}$" />
Upvotes: 1
Reputation: 785058
You can use:
var regEx = /^\d{2}\\\d{2}\\\d{4}$/;
A backslash also requires escaping.
Also note that your original string also needs to have \\
for a literal backslash like this:
var matched = regEx.test('15\\11\\2015')
//=> true
For matching dd/mm/yyyy
regex would be just:
var regEx = /^\d{2}\/\d{2}\/\d{4}$/;
This however would still not invalidate wrong dates like 13/13/2015
Upvotes: 1
Reputation: 4975
The regex is not safe. Consider 99/99/9999
, an improved regex could read /^[0-3]\d\/[01]\d\/[12]\d{3}$/. However this still accept dates like
39/19/2999` which is clearly illeagal.
While you can refine your regex further to limit the seperate numbers to valid ranges it becomes rather complex if you want to rule out feb 31. I recommend doing this with actual code rather than a regex.
Upvotes: 1