HTML5 Form Validation With the “pattern” Attribute

The pattern attribute in HTML5 is used to specify a regular expression (regex) that the value of an input field must match in order to be considered valid. This can be particularly useful for enforcing specific formats for text input fields, such as phone numbers, zip codes, or custom validation rules.

How to Use the pattern Attribute

<form>
    <label for="username">Username (letters only, 3-10 characters):</label>
    <input type="text" id="username" name="username" pattern="[A-Za-z]{3,10}" title="Username must be 3-10 letters long and contain only letters." required>
    <br><br>

    <label for="phone">Phone Number (10-digit number):</label>
    <input type="tel" id="phone" name="phone" pattern="\d{10}" title="Phone number must be 10 digits long, without any dashes or spaces.">
    <br><br>

    <label for="zipcode">ZIP Code (5 digits or 5+4 digits):</label>
    <input type="text" id="zipcode" name="zipcode" pattern="\d{5}(-\d{4})?" title="ZIP Code must be either 5 digits or 5 digits followed by a hyphen and 4 more digits.">
    <br><br>

    <input type="submit" value="Submit">
</form>

Explanation of the Regex Patterns

  • [A-Za-z]{3,10}: Matches a string containing only letters (both uppercase and lowercase), with a length between 3 and 10 characters.
  • \d{10}: Matches exactly 10 digits. \d represents a digit, and {10} specifies that there must be exactly 10 of them.
  • \d{5}(-\d{4})?: Matches either 5 digits or 5 digits followed by a hyphen and 4 more digits. The (-\d{4})? part makes the hyphen and the following 4 digits optional.

Attributes Used with pattern

  • title: Provides a message that will be displayed if the input does not match the pattern. This message is used by the browser’s default validation behavior.
  • required: Makes the field mandatory to fill out.

Custom Error Messages and Validation

The title attribute is used to specify the error message shown when the input does not match the pattern. Custom JavaScript can also be used for more sophisticated validation and error messaging.

Here’s an example of how to use JavaScript to provide custom validation feedback:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pattern Validation Example</title>
</head>
<body>
    <form id="myForm">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" title="Please enter a valid email address.">
        <br><br>
        
        <label for="username">Username (alphanumeric, 4-12 characters):</label>
        <input type="text" id="username" name="username" pattern="[a-zA-Z0-9]{4,12}" title="Username must be 4-12 alphanumeric characters.">
        <br><br>

        <input type="submit" value="Submit">
    </form>

    <script>
        document.getElementById('myForm').addEventListener('submit', function(event) {
            const username = document.getElementById('username');
            if (!username.checkValidity()) {
                alert(username.title);
                event.preventDefault(); // Prevent form submission
            }
        });
    </script>
</body>
</html>

administrator

Leave a Reply

Your email address will not be published. Required fields are marked *