To prevent the form from sending, just use Event.preventDefault
:
I’m not sure what your HTML looks like, exactly, but I’m sure you can adapt the lines with document.getElementById
and make sure that your form has a method
and action
attribute and no inline event handlers (i.e. onsubmit="…"
) are used.
// Assuming the DOM is loaded at this point.
var yourForm=document.getElementById('yourForm');
yourForm.addEventListener('submit',function(e){
"use strict";
/* If you want to use variables,
make sure to update their value before checking. */
var dateField=document.getElementById('dateField').value,
timeField=document.getElementById('timeField').value;
if(!dateField || !timeField){ // Validation
// Message
if(!dateField){
alert("Please select a date.");
}
else if(!timeField){
alert("Please select a time.");
}
// Prevent the form from sending
if(e.preventDefault){
e.preventDefault();
}
else if(e.returnValue){
e.returnValue=false; // For IE8
}
return false; // Just to be safe
}
});
<!-- Here’s a potential HTML structure: -->
<form id="yourForm" action="somewhere.php" method="GET">
<input id="dateField" type="text"/>
<input id="timeField" type="text"/>
<input type="submit"/>
</form>
Setting e.returnValue
is just a way that is compatible with Internet Explorer 8, as pointed out in this SO question. If you want to be fully compatible to these older browsers, you’ll need a compatible version of addEventListener
as well. You can use jQuery for that. And you don’t need to remove return false;
, either.
Also, please be careful when validating your inputs. When comparing against the empty string, use ===
or !==
to avoid type coercion. If you’re sure that the input elements always exist, a simple !field.value
should be sufficient. I recommend validating your code with JSHint.
The above code should cover canceling the submission in most more or less modern browsers. If you still have issues, you can do a workaround and disable the submit button or remove the method
attribute or something like that if the fields are not valid.