I have this chunk of javascript I am trying to use to validate my form. The validation occurs correctly and prevents the submission of the form, but does not display the alert message with the errors that are preventing submission. Through trial and error I discovered
I can use an alert before checking the if time is null, and cannot afterwards. Can anybody explain why?
function validateForm()
{
var good = true;
var errorMessage = "";
var name=document.forms["myForm"]["name"].value;
var startDate = document.forms["myForm"]["date"].value;
if (name==null || name=="")
{
errorMessage = errorMessage + "Name must not be empty.\n";
good = false;
}
if(startDate==null || startDate=="" || checkdate(startDate))
{
errorMessage = errorMessage + "Start date is invalid.\n";
good = false;
}
alert("meow"); //Will happen
if(time==null || time=="")
{
errorMessage = errorMessage + "Start time must be filled out\n";
good = false;
}
alert("meow"); //Will not happen
if(time2==null || time2=="")
{
errorMessage = errorMessage +"End time must be filled out\n";
good = false;
}
if(!checkAfter(time, time2))
{
if(!confirm("Since the end time is after the start time, this competition will end tommorow. Continue?"))
{
good = false;
}
}
alert(errorMessage); //will not happen
alert("meow"); // will not happen
return good;
}
Since there is no
time, the if statement that tries comparing it tonullthrows a reference error, which terminates the script execution.I’m guessing you forgot to get a value from the form and assign it to the
timevariable first.