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

前端 未结 11 1353
长情又很酷
长情又很酷 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:49

    You could also just use regular expressions to accomplish a slightly simpler job if this is enough for you (e.g. as seen in [1]).

    They are build in into javascript so you can use them without any libraries.

    function isValidDate(dateString) {
      var regEx = /^\d{4}-\d{2}-\d{2}$/;
      return dateString.match(regEx) != null;
    }
    

    would be a function to check if the given string is four numbers - two numbers - two numbers (almost yyyy-mm-dd). But you can do even more with more complex expressions, e.g. check [2].

    isValidDate("23-03-2012") // false
    isValidDate("1987-12-24") // true
    isValidDate("22-03-1981") // false
    isValidDate("0000-00-00") // true
    
    • [1] Javascript - Regex to validate date format
    • [2] http://www.regular-expressions.info/dates.html

提交回复
热议问题