Table of Contents
- Introduction
- Application Form HTML (index.html)
- Application Form CSS (styles.css)
- Validation in JavaScript (script.js)
Introduction
The data sent from any form is sent to the server for processing and saved to the database. However, before sending the data for processing, it is necessary to have the data filled properly in correct format, known as client side validation. To validate data with error messages, JavaScript Form Validation techniques can be used.
Have a look into the demo application form with error messages.
Application Form HTML (index.html)
The HTML layout is very simple. We have a form inside BODY tag with fields name, email, country, gender and hobbies (optional). Each field has its own <div> to display error messages. The form has onsubmit attribute that calls a JavaScript function validateForm() that does the validation.
Learn more: About HTML<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation using JavaScript</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()">
<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 value="">Select</option>
<option value="Australia">Australia</option>
<option value="India">India</option>
<option value="US">United States</option>
<option value="UK">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>
<div id="displayData"></div>
</form>
<script src="script.js"></script>
</body>
</html>
Application Form CSS (styles.css)
The styles.css contains the styles for the form, its fields and the error messages.
* {
margin: 0;
padding: 0;
}
body {
font-size: 16px;
background: #f9f9f9;
font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
form {
width: 300px;
background: #fff;
padding: 15px 40px 40px;
border: 1px solid #ccc;
margin: 50px auto 0;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px
}
label i {
color: #999;
font-size: 80%;
}
input, select {
border: 1px solid #ccc;
padding: 10px;
display: block;
width: 100%;
box-sizing: border-box;
border-radius: 2px;
}
.row {
padding-bottom: 10px;
}
.form-inline {
border: 1px solid #ccc;
padding: 8px 10px 4px;
border-radius: 2px;
}
.form-inline label, .form-inline input {
display: inline-block;
width: auto;
padding-right: 15px;
}
.error {
color: red;
font-size: 90%;
}
input[type="submit"] {
font-size: 110%;
font-weight: 100;
background: #006dcc;
border-color: #016BC1;
box-shadow: 0 3px 0 #0165b6;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
input[type="submit"]:hover {
background: #0165b6;
}
Validation in JavaScript (script.js)
All the major tasks for validation is done in script.js file. We have two functions defined; printError and validateForm. The validateForm does the validation and calls the printError method if the validation fails and an error message is to be displayed in any field.
// function to display the error
function printError(elemId, msg) {
document.getElementById(elemId).innerHTML = msg;
}
// Defining a function to validate form
function validateForm() {
event.preventDefault();
var name = contactForm.name.value;
var email = contactForm.email.value;
var mobile = contactForm.mobile.value;
var country = contactForm.country.value;
var gender = contactForm.gender.value;
var hobbies = [];
var hobbiesChkBoxes = document.getElementsByName("hobbies[]");
for (var i=0; i<hobbiesChkBoxes.length;i++) {
if(hobbiesChkBoxes[i].checked) {
hobbies.push(hobbiesChkBoxes[i].value);
}
}
var nameErr = emailErr = mobileErr = countryErr = genderErr = true;
// validate name
if(name == "") {
printError("nameErr", "Please enter your name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if(regex.test(name) === false) {
printError("nameErr", "Please enter a valid name");
} else {
printError("nameErr", "");
nameErr = false;
}
}
// validate email
if(email == "") {
printError("emailErr", "Please 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;
}
}
// validate mobile
if(mobile == "") {
printError("mobileErr", "Please enter your mobile");
} else {
var regex = /^[0-9]\d{9}$/;
if(regex.test(mobile) === false) {
printError("mobileErr", "Please enter a valid mobile");
} else {
printError("mobileErr", "");
mobileErr = false;
}
}
// validate country
if(country == "") {
printError("countryErr", "Please select your country");
} else {
printError("countryErr", "");
countryErr = false;
}
// validate gender
if(gender == "") {
printError("genderErr", "Please select your gender");
} else {
printError("genderErr", "");
genderErr = false;
}
if((nameErr || emailErr || mobileErr || countryErr || genderErr) === true) {
return false;
} else {
// Creating a string from input data for preview
var formData = "You've entered the following details: <br>" +
"<strong>Full Name:</strong> " + name + "<br>" +
"<strong>Email Address:</strong> " + email + "<br>" +
"<strong>Mobile Number:</strong> " + mobile + "<br>" +
"<strong>Country:</strong> " + country + "<br>" +
"<strong>Gender:</strong> " + gender + "<br>";
if(hobbies.length) {
formData += "<strong>Hobbies:</strong> " + hobbies.join(", ");
}
// Display form data
document.getElementById('displayData').innerHTML = formData;
}
}