JavaScript Form Validation


The user-submitted form has to be validated because it may contain values that are incorrect. Consequently, user authentication requires validation. JavaScript offers the ability to do form validation on the client side, which speeds up data processing compared to server-side validation. JavaScript form validation is preferred by the majority of web developers.

Why use Form Validation in JavaScript

Form validation is important because it helps ensure that the data submitted by users via a web form is accurate, complete, and in the correct format. Without proper validation, users can submit incorrect or incomplete data, which can lead to errors, security vulnerabilities, and a poor user experience.

Here's an example of how to validate a simple form using JavaScript.

Example

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function validate() {
var name = document.f1.name.value;
var email = document.f1.email.value;
password = document.f1.password.value;
var passwordlength = document.f1.password.value.length;
var status = false;
if (name == "") {
document.getElementById("namelocation").innerHTML ="Please enter your name";
status = false;
}
else {
document.getElementById("namelocation").innerHTML = "";
status = true;
}
if (email == "") {
document.getElementById("emaillocation").innerHTML = "Please enter your Email";
status = false;
}
else {
document.getElementById("emaillocation").innerHTML = "";
status = true;
} 

if (password == "") {
document.getElementById("passwordlocationRe").innerHTML = "Please enter your password";
status = false;
}
else {
document.getElementById("passwordlocationRe").innerHTML = "";
status = true;
}
if (passwordlength < 6) {
document.getElementById("passwordlocation").innerHTML ="Password must be greater than 6";
status = false;
}
else {
document.getElementById("passwordlocation").innerHTML = "";
status = true;
}
if (status == true) {
alert('Form submitted successfully!');
}
return status;
}
</script>
<form name="f1" action="" onsubmit="return validate()">

<h2>TutorialsTrend - JavaScript Form Validation</h2>
<table style="background:lightgreen;">
<tr>
<td>Name:</td>
<td>
<input type="text" name="name" />
<span id="namelocation" style="color:red"></span>
</td>
</tr>

<tr>
<td>Email:</td>
<td>
<input type="text" name="email" />
<span id="emaillocation" style="color:red"></span> 
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" />
<span id="passwordlocationRe" style="color:red"></span>
<span id="passwordlocation" style="color:red"></span>
</td>
</tr>
<tr><td colspan="2"><input type="submit" value="register" /> </td></tr>
</table>
</form>
</body>
</html>

Output

JavaScript Form Validation

Now click on the register button to check validation.

JavaScript Form Validation

Now filling the form again click on the register button to submit form values.

JavaScript Form Validation
Prev Next