Complete Guide for Form Validation with Javascript

by Aleksandar Pavlov

7 min read

Every developer stumbles upon a client having various requests for form validation. From a multi-step validation to different fields format, smooth address typing, and a flawless user experience… And of course, no page refresh! Because that’s bad, right?! 

If this sounds too familiar and you still don’t have your set of tools to help you get the job done, this article is for you. Read along to see how Javascript developers can use the most useful tools based on Javascript, that will help you easily validate forms on the frontend and provide a great user experience. If you go all the way down, you’ll find a nice little extra.

Full disclosure: We are talking about a form submitted using AJAX, so that means that the first library we have to pull in, is indeed jQuery (mostly because the other tools depend upon it).

Without further ado, let’s get started!

Masking the data to guide the user when filling out the form

In almost every form I’ve worked on there’s always that one field that has special formatting of the data. For some of us, that’s the phone number, for others it’s the routing number, or tax code, or even the credit card expiry date. You know them, you had to do it at least once!

For fields like those, the tool I use due to its flexibility and simplicity is jQuery Mask.

What jQuery Mask allows you to do is to set a specific pattern that the input field must comply with. For example, we can set the Phone field to have the following format: (000) 000-0000

This will format the data like that when the mask is triggered. 

But how do we trigger the mask? Well, that’s easy! We can call it one time like:

$('.phone_us').mask('(000) 000-0000');

Or we can bind it with an event like change:

$('.phone_us').on(‘change’, function () {
$(this).mask('(000) 000-0000');
});

What if I want to support multiple formats?

jQuery mask allows for conditional masking which you can leverage to select the mask to apply. 

You can have different masks for the same element and trigger the mask on the specific event.

In the example above, you can check for the value length or another field value, and based on that switch the mask from (000) 000-0000 to another one based on the criteria.

You can find more examples of dynamic masking here.

Validating the data before submitting the form

It’s Validation time! 

But we have HTML5 validation for the form, isn’t that enough? Oh, cmon, you know it isn’t! How many times you’ve just stripped out the required or disabled from an HTML element to make it valid? I know you did! We all did!

Jokes aside, front end validation is never enough! The main purpose of the front end validation is to assist the user in filling the form, not providing safe data to the server. That being said, we will use our frontend validation to guide the user on how to fill out our form correctly. To that extent, we have different ways of doing it, but custom solutions were my thing… that is until I found out about Parsley! (no, not the plant)

Parsley is a flexible frontend validation tool that makes miracles when it comes to validation. It supports multi-step forms, custom validators, custom error messages, custom error classes, you still need more?

Putting a full example here would be tedious, so here’s the link to the official page where you can find lots of examples. 

Why should I try Parsley?

  1. It allows you to add custom validators. Want to check for a custom date format? You can! Want to check if the sum of the last 9 digits is 42? You can! And all of this by keeping a standardized way to display the errors.
  2. It allows for a step-by-step validation for paginated forms. Very easy and intuitive! You can select the fields to be validated on each step without the need for any additional JS.
  3. It allows both forms and fields validation. So you can validate even a single field if needed.

Go ahead, give it a try!

Disclaimer: Remember that the main purpose of the frontend validation is to guide the users filling out the form providing them with valid feedback about what’s missing or in the wrong format! You should always be validating the data on the server-side as well!

Autocompleting form fields with pre-defined data

One of the features clients most frequently request, or appreciate, is the autocomplete for certain fields like addresses, products, categories, etc. To implement that there are two tools that I mostly use: 

  1. Google Maps Autocomplete
  2. Select2

The Google Maps autocomplete allows you to do a number of things, from locating the user and using their “browser location” to pre-populate the fields, restricting the suggested addresses to a certain area, trigger AJAX calls on a place selection, and much more. If you need to autocomplete an address, Google is the way to go. 

Aside from the address field, for every other field that needs autocompletion based on a set of data, I strongly suggest trying out Select2. It’s amazing with all the features it has! The main ones I use are:

  1. Multiple choice selection.
  2. Custom filtering of data based on given criteria.
  3. Fetching data from API using AJAX.
  4. On choice selection hooks. 

It’s truly a useful tool to achieve a smoother user experience and delight the client. 

Blocking bots from submitting your form

Last but not least, the archnemesis of every public form, the crawlers bots! Guess what’s our solution to them? Google Recaptcha! Preferably V3 with the invisible recaptcha. 

Implementing the invisible recaptcha with AJAX requires some workarounds that you’ll need to get used to. It requires you to manually trigger the validation process before sending the AJAX, then send the AJAX call only when the validation process has been completed. In the callback triggered you’ll be able to get the response token from the recaptcha. Add that to the AJAX request payload and send the call. 

Don’t forget to use the token on the server to validate that it’s authentic!  

How would this affect the website optimization?

But all of these libraries would affect my site speed and score!

Yes, they will! That’s why we have to be considerate when to use them. You should not load Select2 if there is no field to apply it to! 

But I have it in the other form! I can’t go and check form by form and load it conditionally!

Fair enough! That’s why you should include them before the end body tag and defer them!

Yes, but the number of requests would still be higher than without them!

If it’s the number of requests that bothers you or the delivery of those libraries, then another approach is to download them locally (except the recaptcha and maps) and bundle them together in a minified JS file. They are relatively small, and bundling them up allows you to download only one file and have everything. You should still defer it.

Conclusion

Like in most aspects of this industry, there’s not a right or wrong way to do things. It’s just a matter of preference and finding the right tools that will help you speed up the development and handle daily scenarios easily. Above I share my favorite set of tools for handling Javascript form validations, in the hope that you’ll find at least one of them as useful as I did.

Aleksandar Pavlov
Aleksandar Pavlov
Senior Software Engineer

Aleksandar is a full-stack engineer with over 8 years of experience in the industry. Over the years, Aleksandar worked with many international startups to helped them release their products on the market faster. He has a skill for writing insightful (and catchy) posts about technology and loves engaging in discussions on a range of thought-provoking topics. When he's not writing code, you'll find him playing video games or swimming at the local pool.

Expertise
  • JavaScript
  • PHP
  • Laravel
  • MySQL
  • Node.js
  • ReactJS
  • Git
  • PostgreSQL
  • Vue.js
  • Bash
  • +5

Ready to start?

Get in touch or schedule a call.