Regex to validate dates in this format d/m/yyyy

后端 未结 3 2003
隐瞒了意图╮
隐瞒了意图╮ 2020-12-20 03:03

I found a regex that works wonders,but it forces leading 0\'s on month and day and I need to accept dates that have the month and/or day in a single digit format

相关标签:
3条回答
  • 2020-12-20 03:46

    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 讨论(0)
  • 2020-12-20 03:46

    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 :)

    0 讨论(0)
  • 2020-12-20 04:02

    ^(((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.

    0 讨论(0)
提交回复
热议问题