开发者

javascript validate uk date

开发者 https://www.devze.com 2023-03-08 03:34 出处:网络
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\'

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'

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. Try inputting the ID of the object into the function instead. Also, the DOM object's value is used inside of the function, so be sure that's what contains the date:

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/

0

精彩评论

暂无评论...
验证码 换一张
取 消