I found a regex that works wonders,but it forces leading 0's on month and day and I need to accept dates that ha开发者_运维问答ve the month and/or day in a single digit format
I tested this with REGex Tester:
^(((0?[1-9]|[12]\d|3[01])\/(0?[13578]|1[02])\/((1[6-9]|[2-9]\d)\d{2}))|((0?[1-9]|[12]\d|30)\/(0?[13456789]|1[012])\/((1[6-9]|[2-9]\d)\d{2}))|((0?[1-9]|1\d|2[0-8])\/0?2\/((1[6-9]|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0?[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$
This is the same @ant18 linked, but I added ?
for every leading 0
.
EDIT: sry misread the asker's name, corrected
^(((0?[1-9]|[12]\d|3[01])\/(0?[13578]|1[02])\/((1[6-9]|[2-9]\d)\d{2}))|((0?[1-9]|[12]\d|30)\/(0?[13456789]|1[012])\/((1[6-9]|[2-9]\d)\d{2}))|((0?[1-9]|1\d|2[0-8])\/0?2\/((1[6-9]|[2-9]\d)\d{2}))|(29\/0?2\/((1[6-9]|[2-9]\d)(0?[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$
Same as your provided regexp with optional leading 0s.
this will do it:
var rx = /^(3[0-1]|[0-2]?[0-9])\/(1[0-2]|0?[0-9])\/[0-9]{4}$/;
rx.text('01/01/2000'); //true
rx.text('1/1/2000'); //true
rx.text('32/1/2000'); //false
rx.text('1/13/2000'); //false
However this will not really ensure a valid date since it will allow dates like 31/2/2000
To parse a date, and validate it split on /
and use new Date
to create a date object from the values, then extract the same values and see if they match, if not the date is invalid :)
精彩评论