Implementing form validation plays a vital role in preventing malevolent users from entering gibberish text into the form fields. Also, it restricts inexperienced users from erringly entering wrong information in the form.
Of course, you wouldn’t want to collect incorrect data from users in an insecure manner. So, it is imperative for you to define validation rules for forms.
For years, we’ve been using the complex and TL;DR (i.e. Too long; didn’t read) JavaScript code for implementing form validation on the client side. Thankfully, with the release of “HTML5 form validation” we can now add validations to a form with minimal JavaScript.
While the latest HTML version release offers several benefits, however, the most important one is that it comes shipped with plenty of new input fields and attributes essential for validating a form without the need to write complicated JS (short for JavaScript) validation code.
But remember that users can easily become frustrated when filling out a form, especially when they get to know that the data they entered was wrong can increase their frustration to a greater extent. But thanks to HTML5, adding floating input labels can validate the form data at the same time when users fill out the form. This way users will immediately know in case they’re making any mistake in the input fields.
For example, below is an image posted on Dribble by Matt Smith that demonstrates how the floating label pattern works when applied to a form:
This post covers how you can implement floating input labels when adding validations to an HTML5 form.
Most of you might want to know the process of validating an HTML5 form first. After all, not all of you may have experience in writing validation code for an HTML5 form. Also, possible you won’t be having knowledge of the newly introduced input fields and attributes in HTML5.
A Detailed Overview of HTML5 Form Validation
When you plan on validating a form, it is advised that you should begin with the server-side validation first. And, in case you’re a good web designer proceed with adding client-side validation, helping your users get instant feedback whether they’re filling out the form with correct data or not. For instance, providing immediate feedback to users when they are entering data in the email address field will let them know that the email address they entered was valid.
One of the great HTML5 features is that it helps implement client-side validation without depending on the scripts. Rather you can perform such task by making use of “validation attributes” on your form elements. Most importantly, you just need to add the “required” attribute for an input field while the rest is taken care of by your browser.
Here’s an example that will explain the use of required attribute for adding validation to an input field:
Name: <input type="text" name="yourname" required>
The above line of code makes your browser aware that the name INPUT field should be considered as mandatory (i.e. it cannot be left blank).
As you can see a red marker is displayed in the text box corresponding to ‘Your Name’ input field. But as soon as some text is entered in the name input field, the marker turns to a tick-mark indicating that the entered value is valid.
Apart from <input type="text">
(i.e. the text input types), HTML5 now supports several new input options like search, email, tel, datetime, etc. In simple words, with HTML5 we can write the below line of code:
<input type="text" name="email">
into something like:
<input type="email" name="email">
Desktop browsers will render the above code just like any standard text field.
One more important thing I would want to bring to your notice is that: when you’ll try to enter the attributes such as required or input type=”email” in the CodePen demo even without any content, you’ll still get an error message on clicking on the ‘SUBMIT’ button without any valid email address:
In the example we’ve discussed above, you can see that the browser by default displays an error message. But what if you would like to apply your own (i.e. custom) validation rule to the input value? This is where the Regex pattern comes in handy.
You might have seen patterns when entering an email address like abc@a. Needless to say, you would want your users to enter a real e-mail address. And, by specifying your own choice of pattern that match with your data will help validate the entered value. For instance, you can ensure that the email matches the pattern containing three characters or more at the end. To do so, you’ll need to use “Pattern attribute” and Regular Expressions (RegEx).
RegEx is basically a language that is used to parse or manipulate the text. Most often, regular expressions are used to carry out complex operations (such as search and replace) for better formation of the text data. Today, you can find the use of regular expressions in almost every programming and scripting languages. RegEx can be used for validating the data entered in the form fields, by enforcing them on input types utilizing the pattern attribute as follows:
<input id="phone" placeholder="111-111-1111" title="Text to convey pattern for telephone number" required pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
Also, if any validation errors occurs, you can choose to determine a title attribute along with the validation error to throw a message besides “Wrong format!” using the below given line of code:
<input type="email" placeholder="Email" required pattern="^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$" title="Kindly enter a valid email address here.">
Bear in mind, you don’t need to write any absurd pattern for each and every input. Instead, in many cases you’ll just need to assign required attribute to some particular type of data. For instance, a number over 8 will look like:
<input type="number" min="8" required>
Also, keep in your mind that not all of the browsers provide support for all the available validation attributes. Take, for example, the Firefox browser is not compatible with the “minlength” pattern.
The biggest advantage of implementing HTML5 form validation is instant feedback. Mostly, a sort of indication will be highlighted while users fill out some field in a form, to inform them whether the entered value was valid or not.
Now, when you input something in the text box the border color changes to green as follows:
However, as you can see, there is a downside to this approach. Even when adding an invalid (or incomplete) value in the ‘First Name’ field, the user gets an indication that the value is correct. Perhaps, you may think about adding :invalid:not(:empty)
into the code. Unfortunately such logic won’t work with the browsers since they usually consider form elements to be empty.
Wondering what to do?
You can try adding the new pseudo-selector called “:placeholder-shown” in the code as follows:
<form> <label> <span>First Name</span> <input type="text" pattern=".{4,}" placeholder=" " required title="Enter at least 4 characters."> </label> <button>Submit</button> </form>
But most of the browsers does not seem to provide support for placeholder-shown, so it’s better for you to write a script to toggle a class when the input field is empty or not. Here’s the JavaScript code for the same:
$('input:empty, textarea:empty').addClass('empty'); $('input').keyup(function () { if ($(this).val().trim() !== '') { $(this).removeClass('empty'); } else { $(this).addClass('empty'); } });
NOTE: Remember to remove the placeholder element from the above HTML markup.
Now when you run the above code snippet along with HTML5 markup, the output will look like:
As you can see the color of the text box remains red till the validation applied to the field is not fulfilled. And clicking on Submit displays an error message on entering an incomplete name.
But, as soon as the user enters the complete (exceeding 3 characters) the color of the text box border changes to green.
And now, let’s discuss the approach of adding floating input label when validating your HTML5 form. Doing so, helps in enhancing the look and feel of the form. Here’s the HTML markup.
To implement the float label pattern, you’ll have to push the tag right beneath the <input>
element in your HTML markup:
<form> <label> <input type="text" pattern=".{4,}" required title="Characters should not be less than 4."> <span>Your Name</span> </label> <label> <input type="email" required pattern="^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$" title="Please enter a valid email."> <span>Your Email</span> </label> <button>Submit</button> </form>
CSS will look something like:
label { position: relative; display: inline-block; } label span { position: absolute; left: 20px; top: -2em; font-size: .75em; cursor: text; color: #f27853; transition: all 150ms ease; } input { border: 1px solid #f2f2f2; outline: none; } input:focus { border-color: #d9d9d9; } input:valid { border-color: #42d142; } input:invalid { border-color: #ff8e7a; } input.empty { border-color: #d9d9d9; } input.empty + span { top: 50%; transform: translateY(-50%); font-size: 1em; background: none; color: #cccccc; } body { display: flex; min-height: 100vh; background: #f1f1f1; font-family: 'Lato', sans-serif; font-size: 150%; } form { margin: auto; } input, button { padding: 15px 20px; border-radius: 1px; border: 2px solid #bdbdbd; } button { border-color: #363636; background: #363636; color: #FFFFFF; }
And finally, write the JavaScript code:
$('input:empty, textarea:empty').addClass('empty'); $('input').keyup(function () { if ($(this).val().trim() !== '') { $(this).removeClass('empty'); } else { $(this).addClass('empty'); } });
Output:
You can implement several effects when using floating input labels in HTML5, such as:
When working on implementing validations to an HTML5 form, you need to be familiar with:
Implementing validations to a form is crucial for adding an extra layer of security to your site. This is because it prevents nefarious users from adding malicious text as the value in your form fields. Besides, providing instant feedback to users when they’re entering some input to a validated-input field of the form will help enhance their experience. After all, they won’t have to spend time recognizing that they made a mistake in filling the form. But, validating a form using JavaScript alone can be challenging. This is where HTML5 form validation comes to your rescue.
When applying validations to a form using HTML5, you don’t need to write long lines of complex JS code. Instead, you can implement form validation rules with minimal JavaScript coding. Most importantly, many new features are available with the HTML5 form validation such as floating input label that make a form look gorgeous, encouraging users perform form submission.