Form required attribute with a custom validation message in HTML5

HTML5 includes a number of built-in form validation features that allow developers to easily add validation to their forms. One of these features is the "required" attribute, which specifies that an input field is required and must be filled out before the form can be submitted.

The "required" attribute is a boolean attribute. If any input field with the "required" attribute is present in the form, then this field must be completed before submitting the form.

If that particular field is left blank before submitting the form, the user will see an error message from the browser informing them that the input field is necessary.

Using the "required" Attribute

To use the "required" attribute, simply add the attribute to the input field that you want to make required:

<html>
<body>
   <form>
      <label for="name">Name:</label>
      <input type="text" id="name" required>
      <button type="submit">Submit</button>
   </form>
</body>
</html>

The browser will verify that the input field has been filled out before submitting the form, and if it hasn't, it will display an error message. Depending on the browser, the default error message may differ, but it typically states that the field is necessary.

Customizing the Validation Message with Title Attribute

We can change the default validation message using the "title" attribute, which provides a custom tooltip message when validation fails:

<html>
<body>
   <form>
      <label for="name">Name:</label>
      <input type="text" id="name" required title="Please enter your name">
      <button type="submit">Submit</button>
   </form>
</body>
</html>

This code will display the message "Please enter your name" to the user if the input field is left empty when the form is submitted.

Using Pattern Attribute for Advanced Validation

HTML5 offers the "pattern" attribute, allowing developers to specify a regular expression that the input must match. The user will see an error message if the input does not follow the required pattern:

<html>
<body>
   <form>
      <label for="name">Name:</label>
      <input type="text" id="name" required pattern=".{3,}" title="Please enter at least 3 characters">
      <button type="submit">Submit</button>
   </form>
</body>
</html>

This code requires the input field to contain at least 3 characters. If the input does not meet this criteria, the message "Please enter at least 3 characters" will be displayed.

Customizing the Error Message Style with CSS

Using CSS, the error message's appearance can be altered. The ":invalid" pseudo-class can be used to select the input field when it is invalid:

<html>
<head>
   <style>
      input:invalid {
         border: 2px solid red;
         background-color: #ffe6e6;
      }
      input:valid {
         border: 2px solid green;
      }
      .error-message {
         color: red;
         font-weight: bold;
         font-size: 12px;
      }
   </style>
</head>
<body>
   <form>
      <label for="name">Name:</label>
      <input type="text" id="name" required pattern=".{3,}" title="Please enter at least 3 characters">
      <button type="submit">Submit</button>
   </form>
</body>
</html>

When an input field is invalid, this code will turn its border red with a light red background. Valid fields will have a green border.

Customizing Error Messages Using JavaScript

JavaScript provides more control over validation messages using the "setCustomValidity" method. This method allows us to set custom error messages dynamically:

<html>
<body>
   <h2>JavaScript Custom Validation</h2>
   <form id="myForm">
      <label for="username">Username:</label>
      <input type="text" id="username" required>
      <button type="submit">Submit</button>
   </form>
   <p id="result"></p>

   <script>
      const usernameInput = document.getElementById('username');
      const form = document.getElementById('myForm');
      const result = document.getElementById('result');

      usernameInput.addEventListener('input', function() {
         const value = this.value;
         
         if (value.length === 0) {
            this.setCustomValidity('Username is required');
         } else if (value.length < 3) {
            this.setCustomValidity('Username must be at least 3 characters long');
         } else if (!/^[a-zA-Z0-9]+$/.test(value)) {
            this.setCustomValidity('Username can only contain letters and numbers');
         } else {
            this.setCustomValidity(''); // Clear custom validity
         }
      });

      form.addEventListener('submit', function(e) {
         e.preventDefault();
         if (form.checkValidity()) {
            result.textContent = 'Form submitted successfully!';
         } else {
            result.textContent = 'Please fix the errors above';
         }
      });
   </script>
</body>
</html>

This JavaScript example demonstrates real-time validation with custom messages. The `setCustomValidity()` method sets a custom error message, and clearing it with an empty string removes the custom validation.

Comparison of Validation Methods

Method Ease of Use Customization Level Real-time Validation
HTML5 required attribute Very Easy Limited No
Title attribute Easy Basic No
CSS styling Medium Visual only Yes
JavaScript setCustomValidity Complex Full control Yes

Conclusion

HTML5 form validation with the "required" attribute provides a solid foundation for ensuring user input quality. By combining HTML attributes, CSS styling, and JavaScript methods, developers can create robust, user-friendly validation experiences that guide users to provide the correct information while maintaining accessibility and browser compatibility.

Updated on: 2026-03-15T23:19:00+05:30

20K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements