DEV Community

Cover image for HTML Input Validation Attribute.
Chrisspotless
Chrisspotless

Posted on

HTML Input Validation Attribute.

Input validation is the process of checking that data entered into a computer system is correct and complete. It involves checking that the input meets specified requirements and constraints, such as being within a certain range of values or having a certain format. Input validation is important because it helps to ensure the integrity and reliability of data in a computer system by preventing invalid or malicious data from being entered. Input validation can be performed using various techniques, such as using regular expressions to validate the format of the input, or using lookup tables to verify that the input is a valid value.

HTML input validation is an attribute that is used to validate user input in an HTML form. It helps ensure that the user enters the correct type of data into a form field and also helps prevent malicious code from being entered into the form.

*HTML5 Input Validation.
*

HTML5 form validation itself, provides basic validation methods like required, min, max etc. With this, you don't need to write a lot of code for client-side validation.

----------
`    <form>
      <label for="email">Email:</label>
      <input type="email" id="email" name="email" required>
      <input type="submit" value="Submit">
    </form>
----------`
Enter fullscreen mode Exit fullscreen mode

In the example above, the required attribute on the input element ensures that the field must be filled out before the form can be submitted. If the user tries to submit the form without entering an email address, a browser's default error message will be displayed next to the email field.
You can also specify other validation like min, max, pattern by using the same attributes

<form>
  <label for="age">Age:</label>
  <input type="number" id="age" name="age" min="18" max="99" required>
  <input type="submit" value="Submit">
</form>
Enter fullscreen mode Exit fullscreen mode

In this example, the form can't be submitted if the number entered is less than 18 or greater than 99.
It's up to you to decide which approach works best for your application. If you want to perform more complex validation or have more control over the appearance of error messages, you might want to use a JavaScript library like jQuery Validation or use the built-in HTML5 form validation.
The intrinsic validation for the type attribute are:

Intrinsic and basic input validations

In HTML, basic constraints are declared in two ways:

  • By choosing the most semantically appropriate value for the type attribute of the <input> element, e.g., choosing the email type automatically creates a validation description that checks whether the value is a valid email address.
  • By setting values on validation-related attributes.

*INPUT TYPE
*

`<input type="email">`

 `<input type="URL">`
Enter fullscreen mode Exit fullscreen mode

Validation Description

  1. The value must be a syntactically valid email address,
    which generally has the format username@hostname.tld
    but can also be local such as username@hostname.

  2. The value must be an absolute URL.

Validation-related attributes

In addition to the type attribute described above, the following attributes are used to describe basic input types and their validation description respectively:


Attribute    Input types                    Validation Description
             supporting the attribute  

pattern      text, search,url, tel,       The value must match the
             email,password.              pattern.                                                                                                                                        

min         range,number,date,month,week, The value must be 
            datetime-local                greater than or                                                                
                                          equal to the value.           

max         range,number,date,month,week, The value must be less      
            datetime-local                than or equal to                                                
                                          the value.     

require    url,tel,email,password,        There must be a value
           date,month,datetime-           (if set).
           local,week,time,number,
           checkbox,radio,file.                   
           also on the <select> and 
           <textarea> elements.

site       date,week,nonth,datetime-local   Unless the step is
           time,range,number.               set to the literal,
                                            the value must be min 
                                            + an integral multiple 
                                            of the step.                                                                                                                                                                                                                     

min-length    text,search,url,tel,email,    The number of 
              password,                     characters (code 
                                            points)points) must 
                                            not be less than                                                                                    
                                            the value of the 
                                            attribute,if non-                                                                                                                 
                                            empty.All newlines are 
                                            normalized to single                                                                                                         
                                            character (as opposed 
                                            to pairs)for
                                            <textarea>.                                                                                                              


max-length text,search,url,tel,email,       The number of 
           password;                        characters
                                            (code points) must not 
                                            exceed the value                                                                                                                  
                                            of the attribute.
Enter fullscreen mode Exit fullscreen mode

Using JavaScript to perform client-side input validation.

There are a few different ways to perform client-side input validation in JavaScript, depending on the specific needs of your application. One common approach is to add event listeners to the form elements that you want to validate, and then check the user's input when the form is submitted or when the element loses focus. Here's an example of how you might use this approach to validate a form with a single text input that is required:

// Get the form element
const form = document.querySelector("#my-form");

// Get the input element
const input = document.querySelector("#my-input");

// Add an event listener to the form
form.addEventListener("submit", function(event) {
  // Prevent the form from being submitted
  event.preventDefault();

  // Get the input's value
  const inputValue = input.value;

  // Check if the input's value is empty
  if (inputValue.trim() === "") {
    // If it is, display an error message
    alert("The input is required!");
  } else {
    // If it isn't, submit the form
    form.submit();
  }
});
Enter fullscreen mode Exit fullscreen mode

You can also validate the form fields when the user leaves the field by adding the eventlistener 'blur' event.


//Add blur event listener
input.addEventListener('blur', (event) => {
    if (event.target.value.length === 0) {
        alert("The input is required!");
    }
});
Enter fullscreen mode Exit fullscreen mode

Input Validation process

Input validation is the process of ensuring that input data is clean, correct, and useful.
There are several ways to perform input validation, including:

1. Data type checking: This involves ensuring that input data is of the correct type, such as text, number, or password.
2. Length checking: This involves ensuring that input data is the correct length. For example, a username might have a maximum length of 20 characters.
3. Range checking: This involves ensuring that input data is within a specific range. For example, a password might have a minimum length of 8 characters.
4. Format checking: This involves ensuring that input data is in the correct format. For example, an email address should contain an '@' symbol and a '.' symbol.
5. Whitelisting: This involves only allowing input data that is on a predetermined list of acceptable values.
6. Blacklisting: This involves blocking input data that is on a predetermined list of unacceptable values.
Enter fullscreen mode Exit fullscreen mode

*Conclusively *
Overall, implementing proper input validation is an essential part of building secure and reliable web applications. By using a combination of HTML attributes, JavaScript code, and server-side validation, developers can perform a variety of checks on user input, including ensuring that fields are not left blank, that input is of the correct data type, and that input conforms to specific patterns or rules. This process helps to prevent errors and inconsistencies in the data, and can also help to protect against malicious attacks.

Top comments (0)