I am trying to validate the user’s input by linking a JS file to validate the inputs. However, when I click the submit button with erroneous data, the form is submitted and no validation error is given.
The form:
<form id="user_form" name="contactForm" action="#" method="GET" onsubmit="return validateForm();">
<p id="first_name" class="input_title">First name <span class="asterisk_red">*</span></p>
<!-- The HTML 5 'Required' attribute will not allow the form to be sent empty. -->
<input class="input_box" type="text" name="first_name" placeholder="Joe" />
<input id="submit_button" type="submit" name="submit" value="Submit"/>
</form>
And the JS I use to validate:
function validateForm(){
/* Validate the first name field of the form */
var fn = document.forms['contactForm'].first_name.value;
/* If the Name string is empty then return false and show warning. */
if (fn == ""){
alert("First name must be filled out");
document.forms['contactForm'].first_name.reset();
return false;
}else if(fn.length <= 2){
alert("Your first name must more than two characters");
document.forms['contactForm'].first_name.reset();
return false;
}
}
I am not sure if you can call reset() on an element. I think you use that method on form object to clear all the fields. IE and FF doesn’t seem to have a problem but Chrome seem to. As a result, chrome doesn’t execute the javascript and submits the form always. Here is fiddle Form Submit and the updated code: