Javascript dd/mm/yyyy 日期检查?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10194464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:15:51  来源:igfitidea点击:

Javascript dd/mm/yyyy date check?

javascripthtmlvalidation

提问by silentauror

I've got a html form field where people can enter dates coded as such:

我有一个 html 表单字段,人们可以在其中输入编码如下的日期:

input type="text" name="dateofbirth" placeholder="dd/mm/yyyy"

I'm trying to find a JavaScript to check that the date is entered in the dd/mm/yyyyformat (so 10 characters, 2/2/4)

我试图找到一个 JavaScript 来检查日期是否以dd/mm/yyyy格式输入(所以 10 个字符,2/2/4)

Any comments would be appreciated. Only first time doing javascript and have been doing well until this hiccup.

任何意见将不胜感激。只是第一次使用 javascript 并且一直做得很好,直到这个小问题。

Edit: code (form name is 'signup)

编辑:代码(表单名称为“注册”)

// JavaScript Document
function validateForm(signup) {
  {
    var x = document.forms["signup"]["dateofbirth"].value;
    var reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
    if (x.match(reg)) {
      return true;
    }
    else {
      alert("Please enter dd/mm/yyyy");
      return false;
    }           
  }
}

回答by irfanmcsd

You can validate date with your provided format via javascript using regular expression. sample code shown below.

您可以使用正则表达式通过 javascript 使用您提供的格式验证日期。示例代码如下所示。

function(input){
  var reg = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
  if (input.match(reg)) {
    alert("Input matched");
  else {
    alert("Please enter dd/mm/yyyy");
  }
}

回答by nickk_can

Have you looked at the Moment.js javascript library?

你看过 Moment.js javascript 库吗?

http://momentjs.com/

http://momentjs.com/

I haven't used it, but I plan to migrate my Javascript code to it.

我没有使用过它,但我计划将我的 Javascript 代码迁移到它。

回答by ron tornambe

The best JavaScript date library I have found is date.js at http://code.google.com/p/datejs/

我发现的最好的 JavaScript 日期库是http://code.google.com/p/datejs/ 上的date.js

It is also culture aware, so to validate your dd/mm/yyyy dates (I assume you are not located in the USA), use Date.parse as follows

它也是文化意识,因此要验证您的 dd/mm/yyyy 日期(我假设您不在美国),请使用 Date.parse 如下

var d1 = Date.parse("01/12/2004"); // returns a valid JavaScript date
var d2 = Date.parse("30/02/2004"); // returns null

回答by Phrogz

Have you looked in the error console of your web browser to ensure no JS syntax or runtime errors are being raised? The JavaScript code that you appended to your question is not validsurprising (you have an extra {and }wrapping your function body).

您是否查看了 Web 浏览器的错误控制台以确保没有引发 JS 语法或运行时错误?JavaScript代码,您添加到你的问题是不是有效的奇怪(你有一个额外{}包装你的函数体)。

Tip: When using a regex to test a string for validity, you should use if (regex.test(str))and not if (str.match(regex))for simplicity and performance and self-documentation.

提示:当使用正则表达式来测试字符串的有效性时,您应该使用if (regex.test(str))and,而不是if (str.match(regex))为了简单、性能和自我文档。

Given your requirements, I would do this:

鉴于您的要求,我会这样做:

function isDDMMYYYY(str){
  return /^\d{2}/\d{2}/\d{4}$/.test(str);
}

However, I would personally change the requirements to allow users to enter one-digit days and months:

但是,我个人会更改要求以允许用户输入一位数的天数和月份数:

return /^\d{1,2}/\d{1,2}/\d{4}$/.test(str);

回答by Mostafa Khedeer

validate Date includes all roles such as 28 feb and 29 in leep year

验证日期包括所有角色,例如闰年的 2 月 28 日和 29 日

function leapYear(year) {
    return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}



function validateDayMonth(day, month, year) {
        var months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
        var days = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"];
        if (months.indexOf(month) != -1 && days.indexOf(day) != -1) {
            if ((month == '02' && day == '29' && leapYear(year) == false) || (month == '02' && day == '30') || (month == '02' && day == '31') || (month == '04' && day == '31') || (month == '06' && day == '31') || (month == '09' && day == '31') || (month == '11' && day == '31')) {
                return false;
            } else {
                var GivenDate = year + '-' + month + '-' + day;
                var CurrentDate = new Date();
                GivenDate = new Date(GivenDate);
                if (GivenDate > CurrentDate) {
                    return false;
                } else {
                    return true;
                }
            }
        } else {
            return false;
        }

    }

回答by Oleg V. Volkov

Look over MDN guide for regular expressions. You will need info on character class that matches digit - search for "Matches a digit character" phrase; and a way to specify exact length of match - search for "Matches exactly n occurrences of the preceding character" phrase in this guide.

查看正则表达式的 MDN 指南。您将需要有关与数字匹配的字符类的信息 - 搜索“匹配数字字符”短语;以及指定匹配精确长度的方法 - 在本指南中搜索“精确匹配 n 个前面的字符”短语。