I need some help in optimizing this block of code. It looks dirty right now.
The following function checks if the EndDate of my grid is valid or not. If it is not valid it turns the bgcolor of the cell to red color with cell-error
class
function onAccrualEndDateChange(current) {
var endDate = $(current).val();
if (endDate != "") {
var actualEndDate = endDate;
if (actualEndDate != null) {
var tempEndDate = parseInt(actualEndDate.getMonth() + 1) + "/" + actualEndDate.getDate() + "/" + actualEndDate.getFullYear();
if (ValidateDate(tempEndDate)) {
var startDate = $(current).closest("tr").find("input[id$='StartDate']").val();
if (startDate != "") {
var actualStartDate = startDate;
if (actualStartDate != null) {
var tempStartDate = parseInt(actualStartDate.getMonth() + 1) + "/" + actualStartDate.getDate() + "/" + actualStartDate.getFullYear();
if (ValidateDate(tempStartDate)) {
if (actualStartDate.getDate() > actualEndDate.getDate() || actualStartDate.getMonth() > actualEndDate.getMonth() || actualStartDate.getFullYear() > actualEndDate.getFullYear()) {
$(current).closest("td").addClass("cell-error");
} else {
$(current).closest("td").removeClass("cell-error");
}
}
else {
$(current).closest("td").addClass("cell-error");
}
}
else {
$(current).closest("td").addClass("cell-error");
}
} else {
$(current).closest("tr").find("input[id$='StartDate']").closest("td").addClass("cell-error");
}
}
else {
$(current).closest("td").addClass("cell-error");
}
}
else {
$(current).closest("td").addClass("cell-error");
}
} else {
$(current).closest("td").removeClass("cell-error");
}
}
This is the code to validate date
function ValidateDate(date) {
//This validates date with leap year in mm/dd/yyyy or mm/d/yyyy or m/dd/yyyy or m/d/yyyy date format.
var regex = new RegExp("^(((0?[1-9]|1[012])/(0?[1-9]|1\\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\\d)\\d{2}|0?2/29/((19|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$");
return (date.match(regex));
}
else
that do the same thing – charlietfl May 29 '14 at 12:03isValid=false
and change that variable along the way. Then just use onetoggleClass
at the end passingisValid
as second argument to determine whether to add or remove class. That would likely remove most of theelse
– charlietfl May 29 '14 at 14:36