Form validation in JavaScript is a technique used to ensure that user input in a web form meets certain criteria before it is submitted to the server. This helps in improving the quality of data submitted by users and prevents unnecessary server requests caused by invalid input.
Automatic HTML Form Validation
HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the
required
attribute prevents this form from being submitted:
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.
Typical validation tasks are:
- has the user filled in all required fields?
- has the user entered a valid date?
- has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
Example
We will take an example to understand the process of validation. Here is a simple form in html format.
Form Validation
Basic Form Validation
- First let us see how to do a basic form validation. In the above form, we are calling validate() to validate data when onsubmit event is occurring. The following code shows the implementation of this validate() function.