Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

HTML & Javascript Form Validation 101 – In-Depth Guide

Learn Javascript

Introduction

The Basics

JS In HTML Variables & Data-Types Operators Arrays Loops Conditions Functions Events

JS & HTML

DOM Form Validation

More

AJAX Object-Oriented JS

INTRODUCTION
THE MAJOR BUGBEAR

Welcome to a guide on HTML and Javascript form validation – This chapter of the beginner’s series is sort of a follow up from my HTML form basics. Form validation has always been kind of a major bugbear since the ancient days… After all, forms can take up all kinds of shapes and it is nearly impossible to have a “standard validation template” to “one size fits all”.

So in this chapter, we will be exploring the basics of HTML form validation and using Javascript to compliment the checks. Read on.

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!

SERVER-SIDE VS CLIENT-SIDE CHECKING

Just one moment before we officially dive into form checking – There is something important you need to understand, and that is, form checking has to be done on both the server and client-side.

  • Client-side checking – What you are trying to do right now, checking the form with HTML and Javascript.
  • Server-side checking – Form checking on the server-side (with PHP, ASP, JSP) after the form has been submitted.

The reason why this is so important is that client-side code can easily be tampered with. Those with a little more Javascript knowledge will just open up the developer’s console, edit a few lines of code, and that’s it. Goodbye and so much for your “safety checks” with Javascript.

So always ensure that more effort is spent on the server-side checks instead, where the users cannot tamper with; Client-side form validation should not be used as the safety net, but only as a means to “beautify” your forms.

VALIDATION BASICS

Quick recap, you create a form using the form tags and sandwich the Input fields inside.

Name: Email: Password: Tel:

The above form will work, but the problem is, it is missing out on all forms of form validation. Once upon a time in the stone age of the Internet, HTML form checking does not exist. But today, things are a lot more convenient, and we only have to add a few form checking attributes.

AttributeDescription
requiredIndicates that this field is required.
maxlengthSpecifies the maximum allowed characters.
minlengthSpecifies the minimum required characters.
patternSpecify your own field checking pattern.

So simply adding a few more attributes to the above example will turn it into a “form with validation”. Yep, even the email and telephone input fields will automatically determine if a valid value is entered.

Name: Email: Password: Tel:

CUSTOM VALIDATION PATTERNS

There are times where you need to define your own checks, and we can do that by using the pattern attribute. But the problem is, you need to know some regular expressions, which is not that simple… We will go through some of the common patterns here.

EXACT MATCH

The simplest and most straightforward check, the user input must match the pattern exactly. This is especially good for checking things like “enter confirm into the text box to proceed”.

Enter "Doge" - 

MATCHING MULTIPLE VALUES

If you are expecting more than one possible entry, you can use the OR expression. Of course, you can OR as many values as you want.

Enter "Doge" or "Cate" - 

MATCHING ALPHABET CASES

We cannot expect everyone to enter “Doge” with the capital D exactly. To cater for some flexibility, we can use a pair of square brackets so it will match either the small or capital letter.

Enter "Doge" - 

So in the above example, it will match “doge” or “Doge”. In the extreme case, you can do:

Enter "Doge" - 

RESTRICTING NUMBERS AND ALPHABETS

Only 0 to 9 allowed - 

Only a to z allowed - 

MATCHING A SERIES OF NUMBERS OR ALPHABETS

Now that you know how to restrict numbers and alphabets, you can easily make it match in a series using curly brackets:

Matches (0 to 9) 3 times - 

In the above example, the pattern will match a series of 3 digits, that is 000 to 999. But if you want to match 0 to 999, you can use:

Matches (0 to 9) 1 to 3 times - 

Similarly, you can use it on alphabets:

Matches (a to z) 3 times - 

The pattern above will match aaa to zzz.

MATCHING TELEPHONE NUMBERS

Let’s say that you want to match a 9 digits phone number (XXX-XXX-XXX)

Or maybe you want to allow spaces as well (XXX XXX XXX)

MATCHING ANY CHARACTERS

You can use a period (.) to match any characters. For example, if you want to match a string that starts with T, followed by any 3 characters then end with X.

You can also use a star (*) to match zero or more times. For example, matching a string that starts with T, followed by any possible number of characters and ends with X

CUSTOM ERROR MESSAGES

By default, HTML will only give you a generic “please fill up this field properly” error message. So if you want to set the custom error messages, you can use the setCustomValidity function when the window loads.

Name: Email: Password: Tel:

CUSTOM JAVASCRIPT CHECK

Now, let’s say that you want to have a consolidated popup error message box instead – We have to first prevent the default HTML form validation from firing up when we submit the form, then define our Javascript:

  • Attach a “novalidate” attribute to the form.
  • Fire a Javascript when the form is submitted – I.E.onsubmit="return check()"
Name: Email: Password: Tel:

This is how we manually write our own Javascript validation, and there are a few things that you should know:

  • The willValidate property returns a true when the field will be validated on submit – We can use this omit the fields that do not need to be validated.
  • Use the checkValidity function to check the field – It returns a true/false value.

THE MICRO CHECKS

So what has exactly gone wrong, and what are you expecting the user to input? Well, if you want, you can use the validity property and define errors down to that micro level.

validity.patternMismatchReturns true when the user input value does not match your specified pattern.
validity.rangeOverflowReturns true when the user input value is over your specified maximum. (For numbers)
validity.rangeUnderflowReturns true when the user input value is below your specified maximum. (For numbers)
validity.stepMismatchRequires the step attribute to be defined. Returns true when the user input value does not match the step value.
validity.tooLongReturns true when the user input value is over your specified maximum length. (For characters)
validity.typeMismatchReturns true when all the user input is not the correct syntax. I.E. You are expecting numbers, the user enters characters.
validity.validReturns true when all the validity checks have passed.
validity.valueMissingReturns true when the input field is empty.

An example –

var field = field = document.getElementById("some_field");
if (!field.checkValidity()) {
  if (validity.valueMissing) { error += "Please enter a value"; }
  if (validity.tooLong) { error += "A maximum of 12 characters is allowed"; }
}

TRY IT OUT

Now it’s time to hand the controls back to you – Feel free to copy any of the above code into your own project or play with it on my jsFiddle.

CLOSING
WHAT’S NEXT?

We have come to the end of this short chapter, and I hope it has helped you to better understand forms validation with HTML and Javascript. If you have questions, please feel free to comment below. Happy coding!


DOM AJAX

The post HTML & Javascript Form Validation 101 – In-Depth Guide appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

HTML & Javascript Form Validation 101 – In-Depth Guide

×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×