DEV Community

Cover image for How to Perform Form Validation with HTML and JavaScript
TC Wang
TC Wang

Posted on • Updated on

How to Perform Form Validation with HTML and JavaScript

Why form validation is important

Users use web forms to sign up or fulfill online transactions. If you have user input saving to a database, you better make sure the data collected is in the correct format. Someone could crash your website by putting ridiculous values into forms. 

Form validation can also be a security measure. Letting people put whatever they want into forms opens you up to SQL injections. There're way more reasons why form validation is important, but these are the two that I've seen destroy websites.

Form validation 101

Performing form validation on the front-end (before submitting data to the server) is called client-side form validation. While you can also validate data on the back-end/server-side, I will focus on the client-side.

There're two types of client-side validation: 

  • Built-in form validation (HTML)
  • JavaScript validation

Built-in form validation has better performance than JavaScript but is less customizable. In the following example, I created a form with empty fields.
https://tingchun0113.github.io/form-validation/

Try to type in "Jo" and hit the Register button:
"Jo"

After fixing it, the border of the input field will turn from red to green:
Pass

You can try out other fields as well, but below are the rules I imposed (using built-in form validation): 

  • Full Name: min 3 characters; max 100 characters
  • Phone Number: 3 digits-3 digits-4 digits (1111111111 won't pass)
  • Email Address: "@" has to be included
  • Website URL: "http://" or "https://" has to be included
  • Password: 1 uppercase character, 1 lowercase character, and 1 number

Besides, I used JavaScript validation to ensure that "Password" matches "Confirm Password."

Match passwords


Time to see some codes

Built-in form validation (HTML) provides a bunch of attributes to help validate data. Here're some examples:

* required
* minlength="3"
* maxlength="100"
* pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
* type="email"
Enter fullscreen mode Exit fullscreen mode

Putting them into HTML:

Then, check whether passwords match using JavaScript validation:

if "Password" === "Confirm Password", passwords match
Enter fullscreen mode Exit fullscreen mode

You can find the full JavaScript file and other project files in this repo.


Final thoughts

Just don't forget that you can (and you should) validate the data on the server side. It's the final line of defense before the database. If you find this article useful or have any questions, connect me on LinkedIn or follow me on Medium for more articles.

Top comments (1)

Collapse
 
tingchun0113 profile image
TC Wang

Hey @lukeshiru thanks for your msg! Yeah...the JS part def can be improved a lot. Thanks again for sharing the pseudo selector and setCustomValidity.