简体   繁体   English

JavaScript - 验证日期

[英]JavaScript - Validate Date

I have an HTML text field. 我有一个HTML文本字段。 I want to validate via JavaScript that the value entered is a valid date in the form of "MM/DD/YY" or "MM/D/YY" or "MM/DD/YYYY" or "MM/D/YYYY". 我想通过JavaScript验证输入的值是“MM / DD / YY”或“MM / D / YY”或“MM / DD / YYYY”或“MM / D / YYYY”形式的有效日期。 Is there a function that does this? 有没有这样做的功能?

I sort of assumed there was something like isNaN but I don't see anything. 我有点假设有类似isNaN的东西,但我没有看到任何东西。 Is it true that JavaScript can't validate dates? JavaScript无法验证日期是真的吗?

Is it true that JavaScript can't validate dates? JavaScript无法验证日期是真的吗?

No. 没有。

Is there a function that does this? 有没有这样做的功能?

No. 没有。

You will need to write your own validation function to parse the date format (regex comes to mind) and then determine if it is valid within your specific criteria. 您需要编写自己的验证函数来解析日期格式(想到正则表达式),然后确定它是否在您的特定条件中有效。

You could use javascript's own Date object to check the date. 您可以使用javascript自己的Date对象来检查日期。 Since the date object allows some mucking around with the month and day values (for example March 32 would be corrected to April 1), you can just check that the date you create matches the one you put in. You could shorten this if you want, but it's longer for clarity. 由于日期对象允许使用月和日值(例如3月32日将更正为4月1日),您可以检查您创建的日期是否与您放入的日期相匹配。如果您需要,可以缩短此项,但清晰度更长。

function checkDate(m,d,y)
{
   try { 

      // create the date object with the values sent in (month is zero based)
      var dt = new Date(y,m-1,d,0,0,0,0);

      // get the month, day, and year from the object we just created 
      var mon = dt.getMonth() + 1;
      var day = dt.getDate();
      var yr  = dt.getYear() + 1900;

      // if they match then the date is valid
      if ( mon == m && yr == y && day == d )
         return true; 
      else
         return false;
   }
   catch(e) {
      return false;
   }
}

Check out http://momentjs.com/ . 查看http://momentjs.com/ Using it, this snippet 使用它,这个片段

moment(yourCandidateString, 'MM-DD-YYYY').isValid() 时刻(yourCandidateString,'MM-DD-YYYY')。isValid()

should do the job. 应该做的工作。

I use Bootstrap Datepicker. 我使用Bootstrap Datepicker。 One of the options with the text box disabled should do the trick. 禁用文本框的其中一个选项应该可以解决问题。

http://www.eyecon.ro/bootstrap-datepicker/ http://www.eyecon.ro/bootstrap-datepicker/

If you want to venture into the realms of JQuery there are plenty of validation plugins that include date validation. 如果你想进入JQuery领域,有很多验证插件,包括日期验证。 This plugin is one I've used a few times and has served me well. 这个插件是我用了几次并且很好用的插件

<input type="text" id="dateinput"/>

<script type="text/javascript">
   $(#"dateinput").datepicker({
       buttonImage: "images/calendar.png",
       dateFormat: "yyyy-MMM-dd"
   });

   function validateDate() {
       if ($(#"dateinput").val().trim() == "") {
           // Is a blank date allowed?
           return true;
       }
       var oldVal = $(#"dateinput").val();   // Current value in textbox
       // Now use jQueryUI datepicker to try and set the date with the current textbox value
       $(#"dateinput").datepicker("setDate",$(#"dateinput").val());
       // Check if the textbox value has changed
       if (oldVal != $(#"dateinput").val()) {
           // The datepicker will set something different if the date is invalid
           $(#"dateinput").val(oldVal);  // Set the textbox back to the invalid date
           alert ("date was invalid");
           return false;
       } else {
           // If nothing changed, the date must be good.
           return true;
       }
   }
</script>

There does not appear to be a build-in function which does that. 似乎没有内置函数可以做到这一点。 However, this code is probably what you're looking for: 但是,这段代码可能就是你要找的东西:

<script type="text/javascript">

/**--------------------------
//* Validate Date Field script- By JavaScriptKit.com
//* For this script and 100s more, visit http://www.javascriptkit.com
//* This notice must stay intact for usage
---------------------------**/

function checkdate(input){
    var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
    var returnval=false
    if (!validformat.test(input.value))
        alert("Invalid Date Format. Please correct and submit again.")
    else{ //Detailed check for valid date ranges
        var monthfield=input.value.split("/")[0]
        var dayfield=input.value.split("/")[1]
        var yearfield=input.value.split("/")[2]
        var dayobj = new Date(yearfield, monthfield-1, dayfield)
        if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
            alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
        else
            returnval=true
    }
    if (returnval==false) input.select()
    return returnval
}

</script>

Source: http://www.javascriptkit.com/script/script2/validatedate.shtml 资料来源: http//www.javascriptkit.com/script/script2/validatedate.shtml

This is what I use to validate a date. 这是我用来验证日期的方法。

Date.parse returns NaN for invalid dates. Date.parse为无效日期返回NaN。

This supports both date-only and date+time formats. 这支持仅日期和日期+时间格式。

Hope this helps. 希望这可以帮助。

var msg;
var str = "2013-12-04 23:10:59";
str = "2012/12/42";
var resp = Date.parse(str);
if(!isNaN(resp)) { msg='valid date'; } else { msg='invalid date'; }
console.log(msg);

I suggest you a couple of solutions. 我建议你解决几个问题。

  1. guide the user input with a date picker. 使用日期选择器指导用户输入。 This way you can control the input format. 这样您就可以控制输入格式。 jQueryui datepicker is a popular implementation. jQueryUI的日期选择器是一种流行的实现。

  2. use a js library to manage datetime data type (not an actual datatype in Javascript!!). 使用js库来管理日期时间数据类型(不是Javascript中的实际数据类型!!)。 I suggest you date.js . 我建议你date.js。

Have you googled for something like javascript date validation ? 你有google搜索javascript日期验证的东西吗? It shows up some good information, and a working code example here . 它显示了一些很好的信息,以及这里的工作代码示例。

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

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