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

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

    Just use Date constructor to compare with string input:

    function isDate(str) {
      return 'string' === typeof str && (dt = new Date(str)) && !isNaN(dt) && str === dt.toISOString().substr(0, 10);
    }
    
    console.log(isDate("2018-08-09"));
    console.log(isDate("2008-23-03"));
    console.log(isDate("0000-00-00"));
    console.log(isDate("2002-02-29"));
    console.log(isDate("2004-02-29"));

    Edited: Responding to one of the comments

    Hi, it does not work on IE8 do you have a solution for – Mehdi Jalal

    function pad(n) {
      return (10 > n ? ('0' + n) : (n));
    }
    
    function isDate(str) {
      if ('string' !== typeof str || !/\d{4}\-\d{2}\-\d{2}/.test(str)) {
        return false;
      }
      var dt = new Date(str.replace(/\-/g, '/'));
      return dt && !isNaN(dt) && 0 === str.localeCompare([dt.getFullYear(), pad(1 + dt.getMonth()), pad(dt.getDate())].join('-'));
    }
    
    console.log(isDate("2018-08-09"));
    console.log(isDate("2008-23-03"));
    console.log(isDate("0000-00-00"));
    console.log(isDate("2002-02-29"));
    console.log(isDate("2004-02-29"));

    0 讨论(0)
  • 2020-12-02 12:01

    Since jQuery is tagged, here's an easy / user-friendly way to validate a field that must be a date (you will need the jQuery validation plugin):

    html

    <form id="frm">
    <input id="date_creation" name="date_creation" type="text" />
    </form>
    

    jQuery

    $('#frm').validate({
      rules: {
        date_creation: {
          required: true,
          date: true
        }
      }
    });
    

    DEMO + Example


    UPDATE: After some digging, I found no evidence of a ready-to-go parameter to set a specific date format.

    However, you can plug in the regex of your choice in a custom rule :)

    $.validator.addMethod(
        "myDateFormat",
        function(value, element) {
            // yyyy-mm-dd
            var re = /^\d{4}-\d{1,2}-\d{1,2}$/;
    
            // valid if optional and empty OR if it passes the regex test
            return (this.optional(element) && value=="") || re.test(value);
        }
    );
    
    $('#frm').validate({
      rules: {
        date_creation: {
          // not optional
          required: true,
          // valid date
          date: true
        }
      }
    });
    

    This new rule would imply an update on your markup:

    <input id="date_creation" name="date_creation" type="text" class="myDateFormat" />
    
    0 讨论(0)
  • 2020-12-02 12:04
     moment(dateString, 'YYYY-MM-DD', true).isValid() ||
     moment(dateString, 'YYYY-M-DD', true).isValid() ||
     moment(dateString, 'YYYY-MM-D', true).isValid();
    
    0 讨论(0)
  • 2020-12-02 12:07

    Here's the JavaScript rejex for YYYY-MM-DD format

    /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/

    0 讨论(0)
  • 2020-12-02 12:07

    Working Demo fiddle here Demo

    Changed your validation function to this

    function isDate(txtDate)
    {
    return txtDate.match(/^d\d?\/\d\d?\/\d\d\d\d$/);
    }
    
    0 讨论(0)
提交回复
热议问题