简体   繁体   中英

Variable is undefined after assignment on JavaScript

This is getting frustrating, variable is always undefined after assignment. Please explain what I am doing wrong here.

$(document).ready(function() {
    $("#submitButton").click(function() {
        var startDate = $('#startDate').val();
        var endDate = $('#endDate').val();

        if (!isDate(startDate) && !isDate(endDate))
        {
            alert ('Start Date and End Date is invalid');
            return false;
        }
        ... other condition removed for clarity
    });
});

function isDate(dateText)
{
    var comp = [];
    var comp2 = '';
    var y_length = 0;

    comp = dateText.split('/');
    comp2 = comp[2];
    y_length = comp2.length;

    //invalid if year length is less than or greater than 4 
    if (y_length < 4 || y_length > 4) {
        return false;
    }

    var m = parseInt(comp[0], 10);
    var d = parseInt(comp[1], 10);
    var y = parseInt(comp[2], 10);

    var date = new Date(y, m - 1, d);

    if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
        return true;
    } else {
        return false;
    }
}

I amg getting ' Cannot read property length of undefined ' on line y_length assignment , this line:

//comp2 here is undefined
y_length = comp2.length;

Additionally, do you have any suggestion on date validation using JavaScript. Thank you.

If dateText doesn't have at least 2 instances of / in it you are going to end up with less than 3 elements after the split so

comp2 = comp[2];

sets comp2 to undefined and

y_length = comp2.length;

will error out. If you are entering a dateText which has 2 (or more instances) of / in it you shouldn't be getting this error. If you are, you will want to check the value of dateText (with an alert or console.log)

You might want to do something like

if (comp.length > 2) {
    comp2 = comp[2];
    ...
else {
    // error handling
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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