Forms are used on webpages for the user to enter their required details that further send to the server for processing. A form is also known as a web form or HTML form. Examples of form use are prevalent in e-commerce websites, online banking, and online surveys to name a few.
Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with the correct information. This was really a lengthy process which used to put a lot of burden on the server.
In this article, you’ll learn how to build Form Validation without using a framework like a third-party library. We’ll build the whole thing from pure CSS and JS, giving us complete control over how it works and look.
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.
- HTML is used to create the form.
- CSS to design the layout of the form.
Validating a form: The data entered into a form needs to be in the right format and certain fields need to be filled in order to effectively use the submitted form. Username, password, and contact information are some details that are mandatory in forms and thus need to be provided by the user.
Using built-in form validation
required: Specifies whether a form field needs to be filled in before the form can be submitted.
maxlength: Specifies the minimum and maximum length of textual data (strings).
max: Specifies the minimum and maximum values of numerical input types.
type: Specifies whether the data needs to be a number, an email address, or some other specific preset type.
pattern: Specifies a regular expression that defines a pattern the entered data needs to follow.
If the data entered in a form field follows all of the rules specified by the above attributes, it is considered valid. If not, it is considered invalid.
When an element is valid, the following things are true:
- The element matches the
validCSS pseudo-class, which lets you apply a specific style to valid elements.
When an element is invalid, the following things are true:
- The element matches the
invalidCSS pseudo-class, and sometimes other UI pseudo-classes (e.g.,
:out-of-range) depending on the error, which lets you apply a specific style to invalid elements.