JS Form Validation

Understanding Client-Side Validation

Web forms are crucial components of web applications used to gather user information such as name, email address, location, and age. However, users may not always provide the expected data. To optimize bandwidth and reduce strain on server resources, it's beneficial to validate form data on the client-side (i.e., the user's system) using JavaScript before sending it to the web server for further processing.

Client-side validation enhances user experience by being faster; validation occurs directly within the user's web browser. In contrast, server-side validation requires user input to be submitted to the server first, and users must wait for a server response to identify and address any issues.

In the next section, we will explore how to implement JavaScript form validation to handle input errors effectively and gracefully.

Note: Client-side validation does not replace server-side validation. It's crucial to validate form data on the server-side even if it has been validated on the client-side, as users can disable JavaScript in their browser.

Form Validation with JavaScript

The form validation process typically involves two main aspects: required fields validation, which ensures all mandatory fields are filled, and data format validation, which checks that the entered data conforms to the expected type and format.

Now, let's dive into it and see how this works in practice.

Creating the HTML Form

First, let's create a simple HTML form that we'll validate on the client-side using JavaScript when the user clicks the submit button. Create an HTML file named "application-form.html" and save the following code in it:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple HTML Form</title>
<link rel="stylesheet" href="style.css">
<script src="validator.js"></script>
</head>
<body>
<form name="contactForm" onsubmit="return validateForm()" action="confirmation" 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>

Building the Form Validation Script

Next, we'll create a JavaScript file that contains our complete validation script.

Let's create a JavaScript file named "validator.js" and include the following code in it. Save this file in the same location where you saved the previous HTML file. Take a careful look at each line of the example code below to understand how JavaScript validation is implemented:

// Defining a function to display error message
function printError(elemId, hintMsg) {
document.getElementById(elemId).innerHTML = hintMsg;
}

// Defining a function to validate form 
function validateForm() {
// Retrieving the values of form elements 
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) {
// Populate hobbies array with selected values
hobbies.push(checkboxes[i].value);
}
}

// Defining error variables with a default 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 address
if(email == "") {
printError("emailErr", "Please enter your email address");
} else {
// Regular expression for basic email validation
var regex = /^\S+@\S+\.\S+$/;
if(regex.test(email) === false) {
printError("emailErr", "Please enter a valid email address");
} else{
printError("emailErr", "");
emailErr = false;
}
}

// Validate mobile number
if(mobile == "") {
printError("mobileErr", "Please enter your mobile number");
} else {
var regex = /^[1-9]\d{9}$/;
if(regex.test(mobile) === false) {
printError("mobileErr", "Please enter a valid 10 digit mobile number");
} else{
printError("mobileErr", "");
mobileErr = false;
}
}

// Validate country
if(country == "Select") {
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;
}

// Prevent the form from being submitted if there are any errors
if((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {
return false;
} else {
// Creating a string from input data for preview
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(", ");
}
// Display input data in a dialog box before submitting the form
alert(dataPreview);
}
};

To retrieve the value of an individual form field, you can use the syntax document.formName.fieldName.value or document.getElementsByName('name')[0].value. However, for form fields that support multiple selections, such as a group of checkboxes, you'll need to use a loop statement as demonstrated in the example above (lines 14 to 21).

In addition, we've employed regular expressions to validate the format of input data. Regular expressions are highly effective for validating user inputs.

Moreover, the script above will display the data entered by the user in an alert dialog box for preview purposes before submitting the form to the web server.

Tip: While you can validate email format using regular expressions, keep in mind that a user might enter an email that is correctly formatted but does not actually exist. For authentic email validation, consider sending a confirmation email to the user and verifying whether the email truly exists or not.

Adding Style Sheet to Beautify the Form

To enhance the appearance of our form, create a file named "style.css" and include the following code in it. Save this file in the same location where you saved the previous two files. These style rules will beautify our form:

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;
}

That's it! Now, open the "application-form.html" file in a web browser and try filling in some data. Observe how the script responds when invalid data is entered into a form field.

To learn more about server-side validation, you can explore the tutorial on PHP form validation.