Forms are an important part of a website. Different websites contain different types of forms, for example, registration, login, or feedback, etc. Data fields have certain constraints imposed upon them, for example, a minimum length, required, or a specific format, etc. These constraints make sure that the information entered is meaningful, and both the website and the client’s information remain secure.
Most of the fields in our form need to be filled by the user. Therefore, we need to make sure that the user does not leave the field empty, i.e., make it required. Consider the following example to see how to do it.
In the above code, input fields name and email are required, and the field message is optional. When the user submits the form, the
validate() method makes sure that the name and email are not empty. If either one of them is, it shows the relevant message and returns false. Otherwise, it gives an alert of Done and returns true. The form is only sent to the server when the validate() method returns true. Here in the action attribute, we have included the same HTML file for demonstration purposes. However, in practical cases, you will send it to the server.
Whenever the input field changes, two checks are performed, email should not be empty, and it should be in the correct format. The correctness of the email address is checked through a regular expression. Whenever the user does not provide an email address or in the incorrect form, the span element with
email_err id shows the relevant message. The variable check remains false if the data format is incorrect. When the user enters the correct data, it becomes true, and the form can be submitted.
Numeric Value Validation
Some fields only require numeric data, such as age or zip code. Let’s validate such input fields.
This is almost the same as the previous example except for the regex. The regular expression checks that the string only contains the numeric value. If you are not comfortable with regex, you can use
This validation involves checking the two fields to have the same value. For example, a password field and a re-type password field both need to be equal.
When the user clicks the submit button, the validate() method is called. It first checks whether the two fields are empty or not. Then, it checks if they are equal. It shows an error message according to the unsatisfied condition.
Validate drop-down list
The following code checks that an empty value is not selected.
The above code shows an error message if the user selects an empty value.
The following code validates the input type radio.
The above code displays an error if no value is selected. Similarly, you can validate the input type checkbox.