I came across two types of form input validation:
1) Form validation via the onclick
attribute of the Submit
button:
<!DOCTYPE html>
<html>
<head>
<title>form</title>
<script>
function validateForm() {
var first = document.forms["myForm"]["fname"].value;
var last = document.forms["myForm"]["lname"].value;
if (first.trim() == "" || last.trim() == "") {
document.getElementById("demo").innerHTML = "Name must be filled out!";
return false;
}
}
</script>
</head>
<body>
<div id="demo" style="color:red"></div><br>
<form name="myForm" action="formHandler.jsp" method="post" target="_blank">
First Name: <input type="text" name="fname"> <br>
Last Name: <input type="text" name="lname"> <br>
<input type="submit" value="Submit" onclick="return validateForm()" >
</form>
</body>
</html>
2) Form validation via the onsubmit
attribute of the <form>
element:
<!DOCTYPE html>
<html>
<head>
<title>form</title>
<script>
function validateForm() {
var first = document.forms["myForm"]["fname"].value;
var last = document.forms["myForm"]["lname"].value;
if (first.trim() == "" || last.trim() == "") {
document.getElementById("demo").innerHTML = "Name must be filled out!";
return false;
}
}
</script>
</head>
<body>
<div id="demo" style="color:red"></div><br>
<form name="myForm" action="formHandler.jsp" onsubmit="return validateForm()" method="post" target="_blank">
First Name: <input type="text" name="fname"> <br>
Last Name: <input type="text" name="lname"> <br>
<input type="submit" value="Submit">
</form>
</body>
</html>
The above two code examples achieve the same purpose of form validation. I am not asking the general difference between onclick
and onsubmit
addressed in this question: What's the difference between onclick and onsubmit? Instead I am asking: Which one is the preferable way to validate a form? Is there any difference between the two methods?