Regex to validate date format dd/mm/yyyy

后端 未结 21 2554
挽巷
挽巷 2020-11-21 06:32

I need to validate a date string for the format dd/mm/yyyy with a regular expresssion.

This regex validates dd/mm/yyyy, but not the invalid

21条回答
  •  不知归路
    2020-11-21 07:12

    In case you are looking for specific format, This works fine for "dd/MM/yyyy" & "dd/MMM/yyyy" date format only based on Alok answer.

    function isValidDateFormatDDMMYYYY(inputDate) {
        var date_regex = /^(?:(?:31(\/)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
        return date_regex.test(inputDate);
    }
    

    Few examples working thru this code -

    • isValidDateFormatDDMMYYYY("15/01/1999") // returns True
    • isValidDateFormatDDMMYYYY("15/Jan/1999") // returns True
    • isValidDateFormatDDMMYYYY("15/1/1999") // returns True
    • isValidDateFormatDDMMYYYY("1/15/1999") // returns False

    Thanks

提交回复
热议问题