How do I validate a date in this format (yyyy-mm-dd) using jquery?

前端 未结 11 1354
长情又很酷
长情又很酷 2020-12-02 11:41

I am attempting to validate a date in this format: (yyyy-mm-dd). I found this solution but it is in the wrong format for what I need, as in: (mm/dd/yyyy).

Here is t

11条回答
  •  孤城傲影
    2020-12-02 11:47

    You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE if everythings check out to be correct or FALSE if anything is invalid. It doesn't get easier then this!

    function validateDate(date) {
        var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
        if (matches == null) return false;
        var d = matches[3];
        var m = matches[2] - 1;
        var y = matches[1] ;
        var composedDate = new Date(y, m, d);
        return composedDate.getDate() == d &&
                composedDate.getMonth() == m &&
                composedDate.getFullYear() == y;
    }
    

    Be aware that months need to be subtracted like this: var m = matches[2] - 1; else the new Date() instance won't be properly made.

提交回复
热议问题