Updated March 18, 2023
Introduction to JavaScript Form Validation
The following article provides an outline for JavaScript Form Validation. Form validation performs the accuracy check on forms created and checks whether the user-submitted information is correct. The validation of forms usually occurs on the server-side, once the required information entered by the client. After the validation of the form, if there is any incorrect information or any field left blank. Then, the server would send the message to the client that the information that has been entered is incorrect or missing. The validation of forms gives the confidence for the customers that all the information that has been entered would be correct or else error would be thrown so that it can be corrected.
Example:
Code:
var y = document.forms["Form"]["f.name"].value;
if (y == "")
{
alert("Name filed is empty");
return false;
}
}
Things that need to be checked while doing form validation:
- Check whether the user left the field empty which must be filled. If it’s empty, then return “Alert Message”.
- Check whether the user entered a number where the numeric value should be entered. For example, contact details.
- Check whether the user entered an alphabetic character in the name field.
- Check for Numeric and Alphabetic characters. If the form field is Alphanumeric. For example, the message field.
- Check whether the user has entered the password correctly in both fields. (Password field, Confirm Password field)
- Also making sure whether all the drop-down and checkbox are marked correctly.
Types of Form Validation
- Client-side form validation
- Server-side form validation
1. Client-side form validation
To avoid strain and unnecessary bandwidth to the server client-side validation is helpful using Jscript. After validating from the client-side you should have another validation from the server-side. The reason for doing one more validation of the server-side is because the user might have disabled JavaScript on their web browser.
Client-side validation consumes less time to validate since the validation happens on the user’s browser and it helps the user to have a better experience. Whereas server-side validation which happens on the server, it requires the user’s input. Then, it needs to be sent to the server before validation and finally, the user must wait for the response from the server to know on which field the error occurred.
Example:
Code:
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationDefault">First name</label>
<input type="text" class="form" id="validationDefault" placeholder="First name" value="Mark"
required>
</div>
<div class="col-md-4 mb-3">
<label for="validationDefault">Last name</label>
<input type="text" class="form" id="validationDefault" placeholder="Last name" value="Otto"
required>
</div>
<div class="col-md-4 mb-3">
<label for="validationDefaultUsername">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend21">@</span>
</div>
<input type="text" class="form-control" id="validationDefaultUsername" placeholder="Username"
aria-describedby="inputGroupPrepend21" required>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="validationDefault">City</label>
<input type="text" class="form-control" id="validationDefault" placeholder="City" required>
</div>
<div class="col-md-3 mb-3">
<label for="validationDefault">State</label>
<input type="text" class="form-control" id="validationDefault" placeholder="State" required>
</div>
<div class="col-md-3 mb-3">
<label for="validationDefault">Zip</label>
<input type="text" class="form-control" id="validationDefault" placeholder="Zip" required>
</div>
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="invalidCheck12" required>
<label class="custom-control-label" for="invalidCheck">Agree to terms and conditions</label>
</div>
</div>
<button class="btn btn-primary btn-sm" type="submit">Submit form</button>
</form>
Output:
2. Server-side form validation
The server-side validation is performed to ensure that all the data has been entered by the user and nothing has been left black or entered incorrectly. Server-side validation makes sure that there are no mistakes in the form entered by the user.
Example:
Code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form validation</title>
<link rel="stylesheet" href="https://cdn.educba.com/css/form-style.css">
<script>
function printError(elemId, hintMsg) {
document.getElementById(elemId).innerHTML = hintMsg;
}
function validateForm() {
var name = document.contactForm.name.value;
var email = document.contactForm.email.value;
var mobile = document.contactForm.mobile.value;
var country = document.contactForm.country.value;
var gender = document.contactForm.gender.value;
var hobbies = [];
var checkboxes = document.getElementsByName("hobbies[]");
for(var i=0; i < checkboxes.length; i++) {
if(checkboxes[i].checked) {
hobbies.push(checkboxes[i].value);
}
}
var nameErr = emailErr = mobileErr = countryErr = genderErr = true;
if(name == "") {
printError("nameErr", "Please enter name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if(regex.test(name) === false) {
printError("nameErr", "Enter valid name");
} else {
printError("nameErr", "");
nameErr = false;
}
}
if(email == "") {
printError("emailErr", "enter your email");
} else {
var regex = /^\S+@\S+\.\S+$/;
if(regex.test(email) === false) {
printError("emailErr", "Please enter a valid email");
} else{
printError("emailErr", "");
emailErr = false;
}
}
if(mobile == "") {
printError("mobileErr", "Please enter mobile number");
} else {
var regex = /^[1-9]\d{9}$/;
if(regex.test(mobile) === false) {
printError("mobileErr", "Please enter a valid mobile number");
} else{
printError("mobileErr", "");
mobileErr = false;
}
}
if(country == "Select") {
printError("countryErr", "Please select country");
} else {
printError("countryErr", "");
countryErr = false;
}
if(gender == "") {
printError("genderErr", "Please select gender");
} else {
printError("genderErr", "");
genderErr = false;
}
if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
return false;
} else {
var dataPreview = "You've entered the following details: \n" +
"Full Name: " + name + "\n" +
"Email Address: " + email + "\n" +
"Mobile Number: " + mobile + "\n" +
"Country: " + country + "\n" +
"Gender: " + gender + "\n";
if(hobbies.length) {
dataPreview += "Hobbies: " + hobbies.join(", ");
}
alert(dataPreview);
}
};
</script>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()" action="/examples/actions/confirmation.php" method="post">
<h2>Application Form</h2>
<div class="row">
<label>Full Name</label>
<input type="text" name="name">
<div class="error" id="nameErr"></div>
</div>
<div class="row">
<label>Email Address</label>
<input type="text" name="email">
<div class="error" id="emailErr"></div>
</div>
<div class="row">
<label>Mobile Number</label>
<input type="text" name="mobile" maxlength="10">
<div class="error" id="mobileErr"></div>
</div>
<div class="row">
<label>Country</label>
<select name="country">
<option>Select</option>
<option>Australia</option>
<option>India</option>
<option>United States</option>
<option>United Kingdom</option>
</select>
<div class="error" id="countryErr"></div>
</div>
<div class="row">
<label>Gender</label>
<div class="form-inline">
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
</div>
<div class="error" id="genderErr"></div>
</div>
<div class="row">
<label>Hobbies <i>(Optional)</i></label>
<div class="form-inline">
<label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>
<label><input type="checkbox" name="hobbies[]" value="movies"> Movies</label>
<label><input type="checkbox" name="hobbies[]" value="music"> Music</label>
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>
Output:
Conclusion
Form validation in JavaScript doesn’t require complex coding, but we should think from the user’s point of view on how they would do mistakes while filling a form and how it can be validated using the various methods. We must make sure that if the user enters the information incorrectly then, the error message on which field the mistake has been occurred and provide instructions on the input format.
Recommended Articles
This has been a guide to JavaScript Form Validation. Here we also discuss the things that need to be checked while doing form validation and its types. You may also have a look at the following articles to learn more –