JavaScript Form Validation
Validating the form submitted by the user is important to prevent
inappropriate values and ensure authentication.
JavaScript enables client-side form validation, making data processing faster
compared to server-side validation. As a result, most web developers prefer
using JavaScript for form validation.
JavaScript allows us to validate various fields, including name, password,
email, date, mobile numbers, and more.
Example
In this example, we will validate the name and password. The name field must
not be empty, and the password must be at least 6 characters long.
In this example, the form is validated upon submission. The user will not
proceed to the next page until the entered values are correct.
<!DOCTYPE
html>
<html lang="en">
<head>
<meta
charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Form
Validation Example</title>
<script
type="text/javascript">
function validateForm() {
var
name =
document.forms["myForm"]["name"].value;
var
password =
document.forms["myForm"]["password"].value;
// Validate name
if (name == "") {
alert("Name must be
filled out");
return false;
}
// Validate password
if (password.length < 6) {
alert("Password must be at least 6 characters long");
return false;
}
return true;
// Allow form submission
if validation passes
}
</script>
</head>
<body>
<h2>Form Validation
Example</h2>
<form name="myForm"
action="/submit" method="post" onsubmit="return validateForm()">
<label
for="name">Name:</label>
<input type="text" id="name"
name="name"><br><br>
<label
for="password">Password:</label>
<input type="password" id="password"
name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>