Dividing up the form contents with div
has no bearing on whether you can invoke a validation function. The problem is that you aren't referring to the element that you want to validate correctly. Your function expects an argument, which you called form
, but your code to invoke the function doesn't pass any arguments, so inside your function, form
is undefined
and therefore you aren't locating the text field you want to validate.
Instead, just reference the element(s) you wish to test:
<form id="myForm" onsubmit="return validateForm();" method="post" action="form-handler.html">
<div>
<label for="firstName">First Name:</label>
<input name="firstName" type="text" placeholder="Jhon">
</div>
<div>
<label for="submit">Submit</label>
<input id="submit" type="Submit" value="send">
</div>
</form>
<script>
function validateForm(evt) {
// Reference the field(s) to validate properly:
if(document.querySelector("[name='firstName']").value == ""){
alert("Error: Input is empty!");
return false;
}
return true;
}
</script>
Now, having said that, don't use inline HTML event attributes, like onsubmit
in the first place. That technique is 25+ years old and won't die the death it deserves because of how often people just copy it without understanding why it shouldn't be used. Instead, follow modern standards and separate all your JavaScript from your HTML. Also, your first label
is not set up correctly. The for
attribute value must match the id
of the element that the label is "for".
<form id="myForm" method="post" action="form-handler.html">
<div>
<label for="firstName">First Name:</label>
<input name="firstName" id="firstName" type="text" placeholder="Jhon">
</div>
<div>
<label for="submit">Submit</label>
<input id="submit" type="Submit" value="send">
</div>
</form>
<script>
// Get a reference to the form and set up a submit event handler
document.getElementById("myForm").addEventListener("submit", validate);
// The argument is automatically passed and represents
// the event itself
function validate(evt) {
//validation failed if first-name input is empty
// Properly reference the element(s) you wish to test
if(document.querySelector("[name='firstName']").value == ""){
alert("Error: Input is empty!");
// Tell the event not to proceed.
evt.preventDefault();
}
}
</script>