JavaScript form validation

Form validation is the way of ensuring that form data entered by the user meets the specified criteria. Let us take the example of a registration form which needs a name, email ID, etc. We want that name not to contain any special characters and the email address should be a valid one like with format [email protected]. So for such kinds of checks, we can validate the form.

Javascript serves the purpose of validating an HTML form to check for any inappropriate values or any empty fields for the form fields like name, password, email, date, mobile number, etc.

Example:

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["Form"]["name"].value;
var y = document.forms["Form"]["password"].value;
if (x == "") {
alert("Name must be filled out.");
return false;
}
else if (y.length < 8)
{
alert("Password must be at least 8 characters long.");
return false;
}
}
</script>
</head>
<body>
<form name="Form" action="/action_page.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="name">
Password: <input type="text" name="password">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Related Topics