Form Validation on the Client Side

Share this article

Forms validation on the client-side is essential — it saves time and bandwidth, and gives you more options to point out to the user where they’ve gone wrong in filling out the form. Having said that, I don’t mean that you don’t need server-side validation. People who visit your site may use an old browser or have JavaScript disabled, which will break client-only validation. Client and server-side validation complement each other, and as such, they really shouldn’t be used independently.

Why is Client Side Validation Good?

There are two good reasons to use client-side validation:

  1. It’s a fast form of validation: if something’s wrong, the alarm is triggered upon submission of the form.

  2. You can safely display only one error at a time and focus on the wrong field, to help ensure that the user correctly fills in all the details you need.

Two Major Validation Approaches

The two key approaches to client-side form validation are:

  • Display the errors one by one, focusing on the offending field
  • Display all errors simultaneously, server-side validation style

While displaying all errors simultaneously is required for server-side validation, the better method for validation on the client-side is to show one error at a time. This makes it possible to highlight only the field that has been incorrectly completed, which in turn makes revising and successfully submitting the form much easier for the visitor. If you present users with all errors at the same time, most people will try to remember and correct them at once, instead of attempting to re-submit after each correction.

Given these advantages, I’ll focus only on validation methods that display one error at a time.

How to Validate Forms

Take for example the following code fragment:

<script type="text/javascript" language="javascript"> 
function validateMyForm() {
if (parseInt(document.forms[0].phone.value)  
       != document.forms[0].phone.value) {
alert('Please enter a phone number, numbers only');
return false;
}

return true;
}
</script>

<form action="handler" onsubmit="return validateMyForm();">
<p>Phone: <input type="text" id="phone" name="phone" /></p>

<p><input type="submit" value="Send" /></p>
</form>

What’s wrong here? Well, if you add another form before this one, the code will try to validate the wrong form.

A better approach would be to include a form name:

function validateMyForm() { 
if (parseInt(document.forms.myForm.phone.value)  
       != document.forms.myForm.phone.value) {

<form id="myForm" name="myForm" action="handler"  
onsubmit="return validateMyForm();">

This is definitely better, but still not portable enough — if you want to reuse some of this validation on another form, you’ll have to do a lot of text replacing first.

So let’s remove the form name:

function validateMyForm(form) { 
if (parseInt(form.phone.value) != form.phone.value) {

<form action="handler" onsubmit="return validateMyForm(this);">

This last method makes use of the object this, which always points to the current object. This makes our code more portable, and saves typing.

Now how about making visitors’ lives a lot easier? Let’s focus on the field that triggered the error, instead of making them find it on their own.

function validateMyForm(form) { 
if (parseInt(form.phone.value) != form.phone.value) {
alert('Please enter a phone number, numbers only');
form.phone.focus();
form.phone.select();
return false;
}

With these changes, the browser will focus on the incorrectly filled out field, and even select the text for the visitor. If scrolling is needed, this will also happen automatically.

Ok, that was pretty good, but don’t you feel that it’s a little too much code for every field? What if we create a simple library of functions that can save lots of typing and download time for the page? Well, next we’ll do exactly this — and we’ll define our basic functions, to make the validation code even shorter.

function validateNumber(field, msg, min, max) {  
if (!min) { min = 0 }  
if (!max) { max = 255 }  
 
if ( (parseInt(field.value) != field.value) ||  
       field.value.length < min || field.value.length > max) {  
alert(msg);  
field.focus();  
field.select();  
return false;  
}  
 
return true;  
}

This function performs the simple validation of a number — it checks whether the field contains digits only, and optionally, if it is within a given range. You’ll note that this code passes the error message as a parameter. To use such a function, we can basically add it to the onsubmit handler, like so:

<form action="handler"  
onsubmit="return validateNumber(this.phone,  
'Please enter a phone number, numbers only', 5, 10);">

Called like this, it will check whether the phone number is numeric, and is more than 5, but less than 10 digits long. Note how the phone object is passed as a parameter? This allows us to focus upon it via the helper function, as opposed to passing the value of the field only.

Another method for validating numbers is to require them to be within a given range. To make the function do this kind of validation, simply change the check line to:

if ((parseInt(field.value) != field.value) ||   
field.value < min || field.value > max) {

If you want to apply more than one check to the form, you can embed several rules in the onsubmit handler. Imagine, for example, that we require first and last name to be entered, in addition to the phone number:

<form action="handler"  
onsubmit="return (  
validateNumber(this.phone, 'Please enter a phone  
       number, numbers only', 5, 10) &&  
validateString(this.firstName, 'Please  
       enter your first name', 3, 15) &&  
validateString(this.lastName, 'Please  
       enter your last name', 3, 15)  
);">

The code requires all validation rules to evaluate to true (with the logical AND - &&). A closer look reveals that it’s very easy to generate this kind of code from a server scripting language… but that’s a whole other article.

function validateString(field, msg, min, max) {  
if (!min) { min = 1 }  
if (!max) { max = 65535 }  
 
if (!field.value || field.value.length < min ||  
field.value.max > max) {  
alert(msg);  
field.focus();  
field.select();  
return false;  
}  
 
return true;  
}

As you can see, the string validation function looks more or less the same; you can also write other functions and combine them with these.

A common field required in many forms on the Web is the user’s email address. I’ve seen a lot of functions to do this, but usually the simplest and easiest way to validate an email address is to use regular expressions.

Now we’ll extend our function, making it possible to define the field as optional.

function validateEmail(email, msg, optional) {  
if (!email.value && optional) {  
return true;  
}  
 
var re_mail = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+  
       ([a-zA-Z])+$/;  
if (!re_mail.test(email.value)) {  
alert(msg);  
email.focus();  
email.select();  
return false;  
}  
 
return true;  
}

To validate a required email you should call it as:

validateEmail(this.email, 'Please enter your email address')

and if you want it to be optional:

validateEmail(this.email, 'Please enter a correct   
email address or leave the field blank', true)

JavaScript cannot be used on its own for validation, but it helps a lot if you have it. The more compact the code you embed into your HTML, the better — it saves download time, and search engines will like you for it!

Frequently Asked Questions (FAQs) about Form Validation

What is the difference between client-side and server-side validation?

Client-side validation is performed in the user’s browser using JavaScript before the form data is sent to the server. It provides instant feedback and improves user experience. However, it can be bypassed by disabling JavaScript or manipulating the code, so it’s not completely secure.

On the other hand, server-side validation is performed on the server after the form data is submitted. It’s more secure as it can’t be bypassed by the user. However, it requires a round trip to the server, which can affect performance and user experience. Therefore, it’s recommended to use both client-side and server-side validation for optimal security and user experience.

How can I implement form validation in PHP?

PHP provides several functions for form validation. For example, you can use the filter_var() function with different filters to validate and sanitize input data. Here’s a simple example of validating an email address:

$email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
}
This code checks if the submitted email address is in a valid format. If not, it displays an error message.

What are some common validation techniques?

Some common validation techniques include required fields, length constraints, pattern matching, and data type checks. Required fields ensure that the user fills in all necessary information. Length constraints limit the number of characters that can be entered. Pattern matching checks if the input matches a specific pattern, such as an email address or phone number. Data type checks ensure that the input is of the correct type, such as a number or date.

How can I display validation error messages?

You can display validation error messages using JavaScript for client-side validation or PHP for server-side validation. In JavaScript, you can use the setCustomValidity() method to set a custom validation message. In PHP, you can store the error messages in variables and display them in the form.

How can I validate a checkbox?

You can validate a checkbox by checking if it’s checked or not. In JavaScript, you can use the checked property. In PHP, you can check if the checkbox value is present in $_POST or $_GET.

How can I validate a dropdown list?

You can validate a dropdown list by checking if a valid option is selected. In JavaScript, you can use the selectedIndex property. In PHP, you can check if the selected value is in an array of valid values.

How can I validate a radio button?

You can validate a radio button by checking if one of the options is selected. In JavaScript, you can loop through the radio buttons and use the checked property. In PHP, you can check if the radio button value is present in $_POST or $_GET.

How can I validate a date?

You can validate a date by checking if it’s in a valid format and if it’s a real date. In JavaScript, you can use the Date object. In PHP, you can use the checkdate() function.

How can I validate a file upload?

You can validate a file upload by checking the file size, file type, and file extension. In JavaScript, you can use the files property. In PHP, you can use the $_FILES array.

How can I prevent SQL injection?

You can prevent SQL injection by using prepared statements or parameterized queries, which separate the SQL code from the data. This prevents the data from being interpreted as code. In PHP, you can use the PDO or MySQLi extension to execute prepared statements.

Martin TsachevMartin Tsachev
View Author

Martin is a Web developer, and he's particularly interested in PHP. He loves sharing his knowledge with other people and he's setup his Website, mtWeb, to do so.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week