javascript regexp, validating date problem

前端 未结 3 655
醉梦人生
醉梦人生 2020-12-22 03:59

I have some code for validating date below:


function validateForm() {
var errFound = 0;       
//var patt_date = new RegExp(\"^((((19|20)(([02468][048])|([1         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 05:01

    Don't do the whole date validation with a regular expression, that's really pushing the limits of what regexps were designed for. I would suggest this procedure instead:

    1. Check date against regexp /^\d{4}-\d{2}-\d{2}$/
    2. Extract year, month, and day using substr() and convert to integers
    3. Use some if statements to validate the integers. Like so:
        if (month == 2) {
            if (day == 29) {
                if (year % 4 != 0 || year % 100 == 0 && year % 400 != 0) {
                    // fail
                }
            }
            else if (day > 28) {
                // fail
            }
        }
        else if (month == 4 || month == 6 || month  == 9 || month == 11) {
            if (day > 30) {
                // fail
            }
        }
        else {
            if (day > 31) {
                // fail
        }
    

    (That could certainly be written more concisely) Alternatively, you could probably perform this validation using Javascript's Date class - you might have to do something like parsing the date, converting it back to a string, and checking if the two strings are equal. (I'm not a Javascript expert)

提交回复
热议问题