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

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

    I recommend to use the Using jquery validation plugin and jquery ui date picker

    jQuery.validator.addMethod("customDateValidator", function(value, element) {
    // dd-mm-yyyy
       var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
       if (! re.test(value) ) return false
       // parseDate throws exception if the value is invalid
       try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
       catch(e){return false;} 
       },
       "Please enter a valid date format dd-mm-yyyy"
    );
    
    this.ui.form.validate({
        debug: true,
        rules : {
        title : { required : true, minlength: 4 }, 
        date : { required: true, customDateValidator: true }
        }
    }) ;
    

    Using Jquery and date picker just create a function with

    // dd-mm-yyyy
    var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
     if (! re.test(value) ) return false
    // parseDate throws exception if the value is invalid
    try{jQuery.datepicker.parseDate( 'dd-mm-yy', value);return true ;}
    catch(e){return false;}
    

    You might use only the regular expression for validation

    // dd-mm-yyyy
    var re = /^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$/ ; 
    return re.test(value) 
    

    Of course the date format should be of your region

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 11:48

    Rearrange the regex to:

    /^(\d{4})([\/-])(\d{1,2})\2(\d{1,2})$/
    

    I have done a little more than just rearrange the terms, I've also made it so that it won't accept "broken" dates like yyyy-mm/dd.

    After that, you need to adjust your dtMonth etc. variables like so:

    dtYear = dtArray[1];
    dtMonth = dtArray[3];
    dtDay = dtArray[4];
    

    After that, the code should work just fine.

    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-02 11:49

    try this Here is working Demo:

    $(function() {
        $('#btnSubmit').bind('click', function(){
            var txtVal =  $('#txtDate').val();
            if(isDate(txtVal))
                alert('Valid Date');
            else
                alert('Invalid Date');
        });
    
    function isDate(txtDate)
    {
        var currVal = txtDate;
        if(currVal == '')
            return false;
    
        var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
        var dtArray = currVal.match(rxDatePattern); // is format OK?
    
        if (dtArray == null) 
            return false;
    
        //Checks for mm/dd/yyyy format.
        dtMonth = dtArray[3];
        dtDay= dtArray[5];
        dtYear = dtArray[1];        
    
        if (dtMonth < 1 || dtMonth > 12) 
            return false;
        else if (dtDay < 1 || dtDay> 31) 
            return false;
        else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) 
            return false;
        else if (dtMonth == 2) 
        {
            var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
            if (dtDay> 29 || (dtDay ==29 && !isleap)) 
                    return false;
        }
        return true;
    }
    
    });
    

    changed regex is:

    var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
    
    0 讨论(0)
  • 2020-12-02 11:51

    I expanded just slightly on the isValidDate function Thorbin posted above (using a regex). We use a regex to check the format (to prevent us from getting another format which would be valid for Date). After this loose check we then actually run it through the Date constructor and return true or false if it is valid within this format. If it is not a valid date we will get false from this function.

    function isValidDate(dateString) {
      var regEx = /^\d{4}-\d{2}-\d{2}$/;
      if(!dateString.match(regEx)) return false;  // Invalid format
      var d = new Date(dateString);
      var dNum = d.getTime();
      if(!dNum && dNum !== 0) return false; // NaN value, Invalid date
      return d.toISOString().slice(0,10) === dateString;
    }
    
    
    /* Example Uses */
    console.log(isValidDate("0000-00-00"));  // false
    console.log(isValidDate("2015-01-40"));  // false
    console.log(isValidDate("2016-11-25"));  // true
    console.log(isValidDate("1970-01-01"));  // true = epoch
    console.log(isValidDate("2016-02-29"));  // true = leap day
    console.log(isValidDate("2013-02-29"));  // false = not leap day

    0 讨论(0)
提交回复
热议问题