Regex to validate date format dd/mm/yyyy

后端 未结 21 2942
挽巷
挽巷 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:04

    For those who look at these and get completely confused, here is an excerpt from my script. Unfortunately, all it does is match valid numbers in a date time input, and 31st Feb will be marked as valid, but as so many have said, regex really isn't the best tool to do this test.

    To match a date in the format 'yyyy-MM-dd hh:mm' (Or indeed in whatever order you please)

    var dateerrors = false;
    var yearReg = '(201[4-9]|202[0-9])';            ///< Allows a number between 2014 and 2029
    var monthReg = '(0[1-9]|1[0-2])';               ///< Allows a number between 00 and 12
    var dayReg = '(0[1-9]|1[0-9]|2[0-9]|3[0-1])';   ///< Allows a number between 00 and 31
    var hourReg = '([0-1][0-9]|2[0-3])';            ///< Allows a number between 00 and 24
    var minReg = '([0-5][0-9])';                    ///< Allows a number between 00 and 59
    var reg = new RegExp('^' + yearReg + '-' + monthReg + '-' + dayReg + ' ' + hourReg + ':' + minReg + '$', 'g');
    $('input').filter(function () {return this.id.match(/myhtml_element_with_id_\d+_datetime/);}).each(function (e) {
        if (e > 0) {
            // Don't test the first input. This will use the default
            var val = $(this).val();
            if (val && !val.trim().match(reg)) {
                dateerrors = true;
                return false;
            }
        }
    });
    if (dateerrors) {
        alert('You must enter a validate date in the format "yyyy-mm-dd HH:MM", e.g. 2019-12-31 19:30');
        return false;
    }
    

    The above script starts off by building a regex object. It then finds all of the inputs whose id's match a certain pattern and then loops through these. I don't test the first input I find (if (e > 0)).

    A bit of explanation:

    var reg = new RegExp('^' + yearReg + '-' + monthReg + '-' + dayReg + ' ' + hourReg + ':' + minReg + '$', 'g');
    

    ^ means start of match, whereas $ means end of match.

    return this.id.match(/myhtml_element_with_id_\d+_datetime/);
    

    \d+ means match a single or a contiguous sequence of integers, so myhtml_element_with_id_56_datetime and myhtml_element_with_id_2_datetime will match, but myhtml_element_with_id_5a_datetime will not

提交回复
热议问题