Form Validation is something we all have to do on daily basis on the frontend because we want to improve user experience.
I will explain some simple ways to validate data using html.
INPUT ATTRIBUTES
HTML provides some attributes that can aid in validating data. Let's take a look at a few of them.
1. Pattern: This specifies a regular expression that the value of an input should be validated against when a form is submitted. This can be used with a number of input types including text
, date
, tel
, email
, password
, etc.
2. Title: This is not used in validating data but to provide more information on what format the data should be provided.
3. Required: This ensures that an input field is not empty when a form is submitted.
4. Minlength: This simply sets the minimum length of a data that is provided in an input field. See an example below.
<input type="text" minlength="4" required>
These attributes can be combined with a number of input types to ensure the right data is provided.
INPUT TYPES
Using the right input type can help validate against incorrect data type. Below are input types you may need for validating your form.
1. Email: Using email
input type for collecting a users email will validate the data to ensure it is in the right format when the form is submitted.
2. Password: This doesn't only validate the password field but it also masks the characters that are typed in. The strength of the password can be specified by passing a regex to the pattern
attribute of the input field.
<input type="password" pattern="(?=.*[a-z]).{6}" title="Must be 6 characters or more and
contain at least 1 lower case letter">
Above is a simple example of a password input field being validated against a regex provided in the pattern attribute. The title attribute carries the text to be displayed when the provided password fails the regex validation.
3. Tel: This basically defines a field for entering a telephone number. It is mainly used for optimising the keyboard on mobile devices. Combining this with the pattern attribute can help validate the data in the tel input field. Take a look at the example below
<input type="tel" pattern="[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}" title="Phone Number format is +99(99)9999-9999">
4. Number: This defines an input field that accepts only numerical values. It allows for restrictions to be set on what range of numbers are accepted.
<input type="number" min="2" max="8">
The above example shows a number input field that only accepts numbers between 2 and 8.
Below is a snippet of some of the things mentioned above being put into good use.
<form id="form" autocomplete>
<input type="text" minlength="4" required>
<input type="email" required>
<input type="tel" pattern="[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}"
title="Phone Number format is +99(99)9999-9999" required>
<input type="password" pattern="(?=.*[a-z]).{6}"
title="Must be 6 characters or more and
contain at least 1 lower case letter" required>
</form>
P.S : Data Validation has to be done on the server-side where a user has no access to, this ensures that the user does not tamper with the data or type of data being worked with on the server. Also In a situation where you want to do some client side testing, you can add a novalidate
attribute to your <form>
element.
HTML has become more powerful in recent years, and it is interesting the things that can be done with it. I will be writing about it a lot. If you liked this, then please ❤️ and follow me here and on Twitter.
Top comments (37)
None of these things actually protect the back end.
I do not entirely agree, because if the data does not pass the client-side validation, it won't even get to the server-side(backend) validation. So technically it does.
User can bypass client-side validation.
True, but still it does not take the away the importance and essence of client-side validation. The point of the article is to share tips of how to validate on the client side with html, it doesn't disregard the server-side validation.
The client side validation enhance the user experience of the end user, too. About security, the backend should be the final layer and have its own validation.
So both of them are important🎉
Very true @d__raptis
Use Ajax for your forms and you can put all of your validation on the back end so it's all in one place. This makes it much easier to test. Some simple JavaScript and css can handle output of messaging. That said, my point was only to draw attention to the fact that these frontend shortcuts offer no security or protection for the back end. Handy for traditional form post methods, but ultimately pointless for more advanced solutions.
Pointless? not really. This has nothing to do with testing this is just basically using HTML to validate the data that is been gotten from a user.
It is not a frontend shortcut, because this does not stop you from performing any server-side validation but rather helps for better validation while delivering good user experiences.
Sending a backend request for every form field is overload. Yes, the backend is the final layer of security, but that doesn't make frontend validation pointless.
I wouldn't bother sending an AJAX request on every field either, but it depends on the complexity of the form and how it was designed. In most real world examples, if you care about data integrity, HTML5 validation is a giant pain for testing since you need to edit the markup to disable it. If you are doing unit testing, could skip manual testing without the client-side validation, but most websites are not configured for unit testing and just as many devs have no idea what that even is.
Personally, I like to do a combination of light client-side and full server-side validation. Javascript will do things like highlight an empty field that is required on blur, but ultimately all validation and messaging is handled in AJAX requests on submit. Again, it depends on the form, but in 20+ years and hundreds of form implementations, I've completely discarded use of HTML5 validation. I was on board when it first came out years ago, but dropped it within a year of applied use. Once you start working with WAS or understand how malicious users attack form handlers, you'll realize that the convenience is not that convenient.
Great, I think I understand you better now, but this sounds more of a matter preference.
There is almost always a matter of preference involved in how you approach technology problems; my only goal from the original comment was to point out to unsuspecting visitors that HTML5 validation, by itself, will not prevent abuse.
True, and the essence of this article was to show tips on how to use HTML to validate the type of data being sent to the server.
In case of unit testing, you can easily add
novalidate
attribute to theform
element to bypass browser validation.I admit, I didn't know that. @nedy I think a brief note about the novalidate property would be a good addition to your article. Preferences aside, it's a great explanation of html5 validation.
Thank you @lawrencejohnson . I'll be sure to add that.
I'd love to hear explanation.
I see this as useful!
I completely agree final validation shouldn't be done on the client because it can be bypassed. But this kind of validation can reduce the number of "not valid" requests to the server. It is good to have one more layer of security in your applications.
Thank you @denislapi for this.
Interesting ways of maximizing the capabilities of HTML5. Thank you for this article.
Front-end validation enhances the user experience. And a great user experience means a higher usage.
Front-end validation does not however secure the application. For security, validation must be done on the server-side as well.
True, the essence here was not to get rid of the server-side validation but to show you ways that HTML can help validate on the client-side.
Hello Nedy, nice article! I'm sure people that are just getting into html5 features will find it extremely useful!
However, i'd like to point out a misconception on your very first sentence "Form Validation is something we all have to do on daily basis on the frontend because we want to ensure the validity of the data sent to the backend." as i think it may mislead newcomers.
As others have said, you absolutely cannot enforce validation on something the user owns ( browser in this case ), because there are plenty of ways of getting around: disable javascript, edit inputs with devtools, make raw post requests ( if these methods sound too technical for a normal user, think about a simple javascript error on a legacy browser you didn't even need to support ).
Security and validity should always be enforced by something the user has no access to: the server.
So why even bother validating user input on the frontend?
The answer is user experience.
If you run on the client the same checks that the server runs, in 99% of the cases you will catch errors before the request is sent, or better, before the user even finishes typing. This way, you will reach the number one goal for the user: to not waste time!
Thank you @matteorigon , reading back now, I see the perspective of which this would sound to a newcomer. The essence of this is to improve user experience and also reduce the amount of calls made to server in order to validate the data sent.
Like I also replied in other comments, I did not write this to take away the essence and important of server-side security and validation.
That said, I will update this to clearly reflect my thoughts.
Best way is validating from back end
You definitely have to validate in the backend for data consistency and security, because frontend validation can be disabled, but having validation in the frontend can significantly improve the user experience.
Thank you @mnrode for clarifying that
You actually have to validate both ways. That way you catch most of it on the frontend and leave the rare /edge cases to be handled by the backend.
I think the type field is very important to allow the browser to also enter cached autocompletion data as well as allow accessibility.
However I would advise against using custom regular expressions und pattern field.
E.g. the password should just be very long, it doesn’t need a lot of special characters. This is just frustrating for the user. Same goes for phone numbers, I’ve seen so many form fields where I couldn’t enter a standard compliant phone number that just drives me crazy. Especially when the form just says it’s invalid but not why.
Thank you @stealthmusic . The regular expressions in the article are just for the purpose of explaining what the pattern attribute does. Using a title attribute can help tell the user what to input in cases where the platform wants a certain type of data.
Awesome article! Quite useful
Thank you Orie
Nice one. Really helpful
Thank you @johngorithm I am glad you liked it
This is a first validation - on client. You need make a second validation on server too.
Correct @vlasales
Usefullll
Thank you Mohammad