简体   繁体   English

如何使用 jquery 验证这种格式 (yyyy-mm-dd) 的日期?

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

I am attempting to validate a date in this format: (yyyy-mm-dd).我正在尝试以这种格式验证日期:(yyyy-mm-dd)。 I found this solution but it is in the wrong format for what I need, as in: (mm/dd/yyyy).我找到了这个解决方案,但它的格式不符合我的需要,如:(mm/dd/yyyy)。

Here is the link to that solution: http://jsfiddle.net/ravi1989/EywSP/848/这是该解决方案的链接: http : //jsfiddle.net/ravi1989/EywSP/848/

My code is below:我的代码如下:

function isDate(txtDate)
{
    var currVal = txtDate;
    if(currVal == '')
        return false;

    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
    var dtArray = currVal.match(rxDatePattern); // is format OK?

    if (dtArray == null) 
        return false;

    //Checks for mm/dd/yyyy format.
    dtMonth = dtArray[1];
    dtDay= dtArray[3];
    dtYear = dtArray[5];        

    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;
}

What regex pattern can I use for this that will account for invalid dates and leap years?我可以为此使用什么正则表达式模式来解释无效日期和闰年?

I expanded just slightly on the isValidDate function Thorbin posted above (using a regex).我稍微扩展了上面发布的 isValidDate 函数 Thorbin(使用正则表达式)。 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.在这个松散的检查之后,我们实际上通过 Date 构造函数运行它,如果它在此格式中有效,则返回 true 或 false。 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

You could also just use regular expressions to accomplish a slightly simpler job if this is enough for you (eg as seen in [1]).如果这对您来说足够了,您也可以使用正则表达式来完成稍微简单的工作(例如,如 [1] 中所见)。

They are build in into javascript so you can use them without any libraries.它们内置于 javascript 中,因此您可以在没有任何库的情况下使用它们。

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).将是一个函数来检查给定的字符串是否是四个数字 - 两个数字 - 两个数字(几乎是 yyyy-mm-dd)。 But you can do even more with more complex expressions, eg check [2].但是您可以使用更复杂的表达式做更多的事情,例如检查 [2]。

isValidDate("23-03-2012") // false
isValidDate("1987-12-24") // true
isValidDate("22-03-1981") // false
isValidDate("0000-00-00") // true

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 ):由于 jQuery 被标记,这里有一种简单/用户友好的方法来验证必须是日期的字段(您将需要jQuery 验证插件):

html html

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

jQuery 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" />

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

I recommend to use the Using jquery validation plugin and jquery ui date picker我建议使用 Using jquery validation plugin 和 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使用 Jquery 和日期选择器只需创建一个函数

// 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当然日期格式应该是你所在的地区

这是 YYYY-MM-DD 格式的 JavaScript rejex

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

 moment(dateString, 'YYYY-MM-DD', true).isValid() ||
 moment(dateString, 'YYYY-M-DD', true).isValid() ||
 moment(dateString, 'YYYY-MM-D', true).isValid();

Just use Date constructor to compare with string input:只需使用Date构造函数与字符串输入进行比较:

 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嗨,它在 IE8 上不起作用你有解决方案吗 – 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"));

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 .我所做的不仅仅是重新排列条款,我还做了它,以便它不会接受像yyyy-mm/dd这样的“破碎”日期。

After that, you need to adjust your dtMonth etc. variables like so:之后,您需要调整您的dtMonth等变量,如下所示:

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

After that, the code should work just fine.之后,代码应该可以正常工作。

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$/);
}

You can use this one it's for YYYY-MM-DD.您可以使用这个用于 YYYY-MM-DD。 It checks if it's a valid date and that the value is not NULL.它检查它是否是有效日期以及该值是否为 NULL。 It returns TRUE if everythings check out to be correct or FALSE if anything is invalid.如果一切都检查正确,则返回TRUE ,如果任何内容无效,则返回FALSE 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;请注意,月份需要像这样减去: var m = matches[2] - 1; else the new Date() instance won't be properly made.否则将无法正确制作new Date()实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM