JSByte: Form Validation using HTML and JavaScript

Happy New Year! I hope you had a wonderful start to the new year and I wish this year brings you all the amazing things 2020 couldn't.
In today's JSByte, we will discuss validating forms using HTML and JavaScript.
We need form validation anytime we are accepting user input. We must ensure that the data entered is in the correct format, lies within a valid range of data (such as for date fields), and does not contain malicious code that could lead to SQL injections. Malformed or missing data can also cause the API to throw errors.
What are the different types of form validations?
There's two ways of doing validation -
1. Client side validation
2. Server side validation
What data should be validated?
Form validation is needed anytime you accept data from a user. This may include:
1. Validating the format of fields such as email address, phone number, zip code, name, password.
2. Validating mandatory fields
3. Checking the type of data such as string vs number for fields such as social security number.
4. Ensuring that the value entered is a valid value such as country, date, and so on.
How to set up client side validation?
1. Using HTML5 attributes
1. Making fields required using required attribute
2. Constraining the length of data using minlength and maxlength for text data and min and max for numerical data
3. Restricting the type of data using type such as - <input type="email" name="multiple>
4. Specifying data patterns using pattern attribute that matches data against a specified regex pattern.
2. Using JavaScript
You can perform JavaScript validation in two ways:
1. Inline validation using JavaScript
2. HTML5 Constraint validation API
For code samples, check out the full article
Don't forget server side validation
Client side validation is not the only validation check you should do. You must also validate the data received from your client on the server side code to ensure that the data matches what you expect it to be.
You can also use server-side validation to perform business logic verifications that should not live on the client side.
TL;DR
Forms can be validated on the client side and server side. Client side is great for providing a great user experience whereas server side is a must for ensuring data is free of malicious code.
--