简体   繁体   English

javascript 验证英国日期

[英]javascript validate uk date

I am trying to validate a date in the format dd/mm/yyyy using a function I have found online, but I get this error: 'input is null'我正在尝试使用我在网上找到的 function 以 dd/mm/yyyy 格式验证日期,但我收到此错误:'input is null'

Can anybody tell me where my syntax is wrong?谁能告诉我我的语法哪里错了?

if (validateDate($("#<%=StartDate.ClientID%>")) == false) {
                alert("not date");
            }
            else {
                alert("date");
            }

function validateDate(dtControl) {
        var input = document.getElementById(dtControl)
        var validformat = /^\d{1,2}\/\d{1,2}\/\d{4}$/ //Basic check for format validity
        var returnval = false
        if (!validformat.test(input.value))
            alert('Invalid Date Format. Please correct.')
        else { //Detailed check for valid date ranges
            var dayfield = input.value.split("/")[0]
            var monthfield = 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.')
            else {
                returnval = true
            }
        }
        if (returnval == false) input.focus()
        return returnval
    } 

You're inputting a jQuery object into the validateDate function when it takes a string ID.当它需要一个字符串 ID 时,您将 jQuery object 输入到 validateDate function 中。 Try inputting the ID of the object into the function instead.尝试将 object 的 ID 输入到 function 中。 Also, the DOM object's value is used inside of the function, so be sure that's what contains the date:此外,DOM 对象的值在 function 内部使用,因此请确保其中包含日期:

if (validateDate("<%=StartDate.ClientID%>") === false) {
    alert("not date");
} else {
    alert("date");
}

Here is an example showing a working version of the code: http://jsfiddle.net/7WJYF/这是一个显示代码工作版本的示例: http://jsfiddle.net/7WJYF/

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

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