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

后端 未结 3 2086
隐瞒了意图╮
隐瞒了意图╮ 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

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

提交回复
热议问题