DEV Community

Cover image for Form Validation with HTML
OpenReplay Tech Blog
OpenReplay Tech Blog

Posted on • Originally published at blog.openreplay.com

Form Validation with HTML

by Chris Ebube Roland

Ever gotten frustrated while filling a form online, and after taking like 2-3 minutes to get it done and finally submit, you get sent back because there was a section in the form that wasn't filled in the needed format or a required field that you happened to miss... then you have to start the whole laboring process all over? That is a problem from a not-too-perfectly designed form.

In that aspect, Form Validation gets involved. We can say that a web form's validation is a "technical procedure where it is checked to see if the data entered by the user is accurate."

Either the form will notify the user that they made a mistake and must correct it before continuing, or the form will be verified, and the user will be able to finish the registration process.

For example, if you are filing a form that requires a valid email address that is incorrectly formatted, a proper form will not submit the form and will give you an error message when you put in an email that isn't in the correct format;

Example illustration 1.

But when you put in your email address in the correct format, it works, and the error message goes away;

Example illustration 2

In essence, validation checks to see if the submitted content is in the appropriate format, for example, if it's an email, user@example.com, and if it meets the requirements for an acceptable input.
e.g., the email isn't already registered, or the password fits the required format.

In this article, we'll discuss what validation is, what types of validations there are, and show examples of forms and validation.

Form validation types

For our browsers to be able to interpret a web form, it has to be validated. Validation done in the browser is called client-side validation, and validation done on the server is called server-side validation. They are the primary means of validation; we will discuss them briefly.

Client-side Validation

Client-side validation is a preliminary check and a key component of a positive user experience. By identifying erroneous data on the client side, users are given the opportunity to correct it right away. A considerable delay results from a circular trip to the server, which is then refused and sent back to the client to notify the user to rectify their data. A quicker response from the browser results in a better user experience. All user inputs are verified in the browser when client-side validation is used. Client-side validation eliminates the need for a server round trip, reducing network traffic and enhancing server performance. Client-side validation exists on the front end and is part of the front-end secure coding requirements. This type of validation is done on the browser side using script languages such as VBScript, JavaScript, or HTML5 attributes.

Here is an example of client-side data validation using just HTML:

<form>
  <div>
    <label for="number">Number</label>
    <input type="number" id="number" pattern="[-+]?[0-9]" />
  </div>

  <div>
    <label for="numberfloat">Numbers with Decimals</label>
    <input
      type="number"
      id="numberfloat"
      step="any"
      pattern="[-+]?[0-9]*[.,]?[0-9]+"
    />
  </div>

  <div>
    <label for="numberrange">Number with a Min and Max Range (3-42)</label>
    <input
      type="text"
      id="numberrange"
      min="3"
      max="42"
      pattern="\[3-9]|[1-3\][0-9]|4[0-2]"
    />
  </div>

  <input type="submit" class="button" value="Submit" />
</form>
Enter fullscreen mode Exit fullscreen mode

Server-Side Validation

When employing server-side validation, the user's input is transmitted to the server and verified using one of the server-side scripting languages, such as Python or Node.js. A new dynamically created web page is used to send the feedback to the client following the server-side validation procedure. To specify the data types a property can take, attributes are attached above the property declaration in the model/entity class to perform server-side validation. The specifications may include a wide range of parameters to ensure that only refined data is accepted.

While client-side input validation is handled by front-end code, server-side input validation is handled by back-end code. Back-end code acts as a bridge between the front-end code (which the user sees) and the database, which stores the user data, as it is the closest to the database.

To take measures that guard against unscrupulous users who can quickly get around your Client Side scripting language and submit potentially harmful information to the server, it is preferable to validate user input on the Server Side.

NOTE: Client-side validation should not be considered an exhaustive security measure! Your apps should always perform security checks on any form-submitted data on the server side as well as the client side because validation at the latter is too easy to bypass, so malicious users can still easily send bad data through to your server. Mostly, the client-side Validation depends on JavaScript, so if users can turn JavaScript off on the browser, it can easily be bypassed and submit dangerous input to the server. So, client-side Validation can not protect your application from malicious attacks on your server resources and databases.
As both the validation methods have their significance, it is recommended that both validations are implemented for maximum security.

The <input> element

The <input> tag is an important element of HTML form. The "type" attribute of the input element can be of various types, which defines an information field.
It can also be said that this tag is an input control that presents users with an interactive control for entering data. Traditionally, the tag is found within the <form> tag and can represent text fields, checkboxes, drop-downs, buttons, and other inputs simply by setting the appropriate type attribute. An example such as <input type="text" name="name"> gives a text box.

Default attributes available to aid validation on the input element.

  • <input type="checkbox"> - A check box allowing single values to be selected/deselected.
  • <input type="email"> - A field for editing an email address. It looks like a text input but has validation parameters and a relevant keyboard in supporting browsers and devices with dynamic keyboards.
  • <input type= "button"> - A push button with no default behavior displaying the value of the value attribute, empty by default.
  • <input type= "color"> - A control for specifying a color; opening a color picker when active in supporting browsers.
  • <input type="date"> - A control for entering a date (year, month, and day, with no time). It opens a date picker or numeric wheels for year, month, and day when active in supporting browsers.
  • <input type="datetime-local"> - Used for entering a date and time, with no time zone. It opens a date picker or numeric wheels for date and time components when active in browsers that support it.

There are also different elements similar to the input tag that is also used in form validation.
A few of them are as follows;

  • label: Several form elements have labels defined by the <label> element. Users of screen readers can benefit from the <label> element because the screen reader will read the label aloud when the user focuses on the input element. Because the text inside the <label> element toggles the radio button or checkbox when the user clicks it, the <label> element also aids users who have trouble clicking on tiny regions (like radio buttons or checkboxes).
    • select: The <select> element can be used to add a drop-down list to your form; it basically defines a drop-down list. The <option> elements define an option that can be selected. By default, the first item in the drop-down list is selected. Here's an example:
<label for="cars">Select car:</label>
<select id="cars" name="cars">
  <option value="Mercedes">Mercedes</option>
  <option value="Ford">Ford</option>
  <option value="Subaru">Subaru</option>
  <option value="Audi">Audi</option>
</select>
Enter fullscreen mode Exit fullscreen mode
  • textarea: The <textarea> element creates a larger area for text input than the default textbox; it defines a multi-line input field (a text area). The cols attribute determines the width of a text area, whereas the rows attribute specifies the number of lines visible in a text area. The <textarea> element also accepts several attributes often used in the form <input>, such as autocomplete, autofocus, disabled, placeholder, readonly, and required.
<textarea name="message" rows="20" cols="40">
The dog was rolling in the grass.
</textarea>
Enter fullscreen mode Exit fullscreen mode
  • fieldset: In a form, related data are grouped using the <fieldset> element. A portion of an HTML form is grouped by the <fieldset> element, which is accompanied by a caption provided by a nested <legend> element. It requires a few attributes, the two most notable being <form> and <disabled> form can contain the <id> of another <form> on the same page, allowing you to make the <fieldset> part of that <form> even if it is not nested inside it, and <disabled> allows you to disable the <fieldset> and all of its contents at once.
<form action="/action_page.php">
  <fieldset>
    <legend>Details:</legend>
    <label for="firstN">First name:</label><br />
    <input type="text" id="firstN" name="firstN" value="John" /><br />
    <label for="lastN">Last name:</label><br />
    <input type="text" id="lastN" name="lastN" value="Doe" /><br /><br />
    <input type="submit" value="Submit" />
  </fieldset>
</form>
Enter fullscreen mode Exit fullscreen mode

Open Source Session Replay

OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.

OpenReplay

Start enjoying your debugging experience - start using OpenReplay for free.

Form validation in HTML

To prevent data with errors from being transferred to the server, HTML form validation involves reviewing the contents of the HTML form page. This procedure is crucial for creating HTML-based web apps since it improves web pages and applications. Both JavaScript and built-in HTML5 features can be used for form validation.

HTML5 form validation

Wherever form validation is brought up, JavaScript is the first language that comes to mind for a fully interactive form. However, HTML5 has provided built-in features for form validation without using JavaScript. Form elements will have validation attributes added, which will enable the form validation for us automatically. Various attributes make this possible with HTML5; they allow us to allocate various instructions on our form elements, such as pattern, minlength/maxlength, and required, which let us set specific rules in our form.

When should you use HTML for form validation? Form validation with HTML should be considered an initial basic security layer for adding JavaScript. As we mentioned earlier in the article, both should be implemented to ensure maximum security against cases where a user might be able to turn off JavaScript and leave your form vulnerable.

How to validate your form in HTML5? Using the form validation tag required, which makes the data in that field mandatory to enter, an example of form validation using the HTML5 validation attribute is provided below. Without the required tag, the form cannot be submitted.

<!DOCTYPE html>
<html>
  <head>
    <style>
      .formData {
        padding-top: 20px;
        padding-bottom: 20px;
        padding-left: 10px;
        background-color: rose;
      }
      form {
        font-size: 30px;
      }
      form input {
        margin-left: 10px;
        font-size: 15px;
      }
    </style>
  </head>
  <body>
    <div class="formData">
      <form action="#">
        Name: <input type="text" name="name" required />
        <input type="submit" />
      </form>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

The result of the above code is a simple web form with only one input data field - Name.

A simple web form 3

Now, if we try submitting the form without providing any information in the name area, we will receive the error message "Please fill out this field" after submitting, and the form won't be sent to the server.

Error message illustration 4

Above is an error message displayed due to submitting the form without inputting any data in the required field.

Constraint Validation

Constraint Validation can be easily explained by saying that each field on a form serves a purpose. Constraints, or the guidelines dictating what should and shouldn't be entered into each form field, are frequently used to guide this purpose.

An algorithm used by browsers to assess a form's validity after submission makes up the main part of constraint validation. For instance, an <email> field will require inputting a correct email address before it can be submitted. A <password> field may have a minimum number of required characters and particular character requirements; a text field may have a character restriction.

Modern browsers can ensure that users adhere to these restrictions and alert users when those rules have just been violated. Constraint validation and the <input> element now have new semantic types, which HTML5 added to make validating the form's content on the client side easier.

By introducing new attributes, simple, everyday constraints can be tested without having to use JavaScript. The algorithm reaches this result by combining the current attributes type and maxlength with the new HTML5 properties min, max, step, pattern, and required.

Conclusion

In this article, we intricately discussed form validations and how they work. We then broke down and explained the sides of validation on the browser(client-side and server-side) with examples and illustrations. Briefly, we looked into the <input> element, and some of its default attributes that aid validation.
We also explained form validation using HTML, how to use HTML for form validation and when it should be implemented. Finally, we discussed constraint validation and its purpose in a form.

A TIP FROM THE EDITOR: For more on form validation, do not miss our Form Validation Using JavaScript's Constraint Validation API article.

newsletter

Oldest comments (0)