How to Use ‘Pattern’ Attribute in HTML5 Form Validation?

Table of Contents

    Have you seen the enquiry form on a website? It starts users’ conversation with a website. Users ask for anything resonating with his intent on the website.  But it is where that user’s inquiry will be stuck if its inquiry form is not working properly. This is a consequence of poor validation. Result? 

    Incorrect data, frustrated users, and extra backend processing are some common consequences of this bad user experience. This problem can be solved by leveraging HTML5, as it has several native validation features to overcome this problem. And the most powerful among them is the pattern attribute.     

    What is Form Validation?

    ‘Validation’ determines the action of checking accuracy. Or you can say, it’s all about proving validity.  Form is an ideal source of communication virtually with the user. Let’s say, you want to create a gmail account. How can you do it? Obviously, you need to fill the form. By providing credentials in the form, your account would be ready to use.

    ‘Form validation’ identifies if the input value is in correct or incorrect format.  Have you noticed an error message that pops up onsubmit or onkeypress or onblur? 

    • Onsubmit: It identifies the validity evaluation when the user submits the form.  
    • Onkeypress: It evaluates the accuracy of input while typing or entering any value into a field. 
    • Onblur: It verifies the input in the form when the user checks the form.

    Any of these validations returns the message in the pop-up that the input in the pointed field requires correction. Mostly, it figures out correction in the format. For example, the input field of the username mandates entering ‘alphabets’ & ‘uppercase’ or ‘lowercase’

    When this given validation criterion does not match, conflict arises. Consequently, the error message pops up while interrupting submission.  

    Let’s move on….

    This blog contains helpful tips regarding web designing of form validation in HTML5. It basically highlights the ‘pattern’ attribute. Go through these ‘how-to-use’ tips, practical examples, best practices, and limitations for delivering a flawless user experience.  

    What Is the pattern Attribute?

    The pattern attribute is a very common feature of HTML 5 that uses <input> elements for a regular expression (regex). The value must match these elements before a user submits the form. 

    A slight mismatch with the defined pattern leads to these results automatically:

    • Form submission stops.
    • A validation error message pops up.
    • The invalid field highlights. 

    These are client-side errors, which help in improving user experience and reducing invalid data in your server.  

    Basic Syntax of pattern

    <input type=”text” pattern=”regex” title=”Error message”>

    This syntax is for designers who use it to put values against: 

    • pattern: That carries the regular expression
    • title: It displays a comprehensive message when entered data is invalid. 

    These elements work best when they are combined with required, which mandates the entry as per the field’s requirement in the form. The browser thereafter checks the input value put against the regex at the time of form submission. 

    Input Types That Support pattern

    The pattern attribute shows expected results when it consists of the following input types:

    • text
    • search
    • tel
    • url
    • email
    • password

    With type=”number”, it does not show expected results.

    Simple and Practical Examples

    Let’s explain it witht some practical cases. 

    1. Validating Names (Letters Only): It necessitates entering valid names by following these codes:

    <input

      type=”text”

      name=”fullname”

      pattern=”[A-Za-z ]+”

      title=”Only letters and spaces are allowed”

      required>

    The validation rule will check whether the name has only letters and spaces. If it consists of special elements (like #, $, @, etc.) or numbers, the entry will be denied, showing as INVALID. 

    2. Checking a 10-Digit Phone Number: It allows entering only numbers, but no text. 

    <input

      type=”tel”

      pattern=”[0-9]{10}”

      title=”Enter a valid 10-digit mobile number”

      required>

    As the code runs, it validates the fed data. If the user enters exactly 10 digits with no spaces or symbols, it passes the query as valid.

    3. Password Validation (Alphanumeric): It takes the combination of alphabet and numbers. 

    <input

      type=”password”

      pattern=”[A-Za-z0-9]{8,16}”

      title=”Password must be 8–16 characters long and contain only letters and numbers”

      required>

    This example proves password validation, which limits passwords’s length to 16 characters, including letters and numbers.

    Using Anchors for Clarity

    However, browsers are smart enough to automatically match the entire input value. But anchors make regex more understandable and intentional.

    Here is an example of the code:

    <input

      type=”text”

      pattern=”^[0-9]{6}$”

      title=”Enter a 6-digit PIN code”>

    • ^ → It marks the start of the input. 
    • $ → The input ends with this sign. 

    This is how even partial matches are prevented. 

    Common Real-World Use Cases

    Field TypeRegex Pattern
    Australian PIN Code/^[0-9]{4}$/
    Username[a-zA-Z0-9_]{5,15}
    Hex Color Code#?[A-Fa-f0-9]{6}
    Employee ID[A-Z]{3}[0-9]{4}

    These patterns automatically validate entries and standardise data at the point of entry. 

    Combining pattern with Other Attributes

    If you want stronger validation specifications, combine pattern with:

    • required
    • minlength
    • maxlength
    • placeholder

    Example:

    <input

      type=”text”

      pattern=”[A-Z]{3}[0-9]{4}”

      minlength=”7″

      maxlength=”7″

      placeholder=”ABC1234″

      title=”Format must be ABC1234″

      required>

    This pattern brings consistency and also feeds usable data into the database. 

    Custom Error Messaging with title

    HTML5 is considered the best web design tool because it automatically pops the title value when the entry fails to meet a valid value. So, you don’t need to write extra codes in JavaScript to notify customers. It automatically does it. 

    <input

      type=”text”

      pattern=”[0-9]{4}”

      title=”Please enter exactly 4 digits”>

    Tip: Always write error messages in a layman’s language, but not in a regex explainer.  

    Limitations of the pattern Attribute

    The pattern has some constraints also, which are shared below: 

    • It cannot manage or handle complex logic or conditions. 
    • Ranges and calculations cannot be verified in it. 
    • It fails to replace server-side validation. 
    • Errors styling is limited across browsers

    Here, the concern is easy bypassing of client-side validation. It can be easy to bypass with the pattern attribute. But server-side validation is necessary if you want tighter security and data integrity. 

    Best Practices for Using pattern

    All in all, the designer or developer should:

    • Use a pattern to validate the format but not business rules.
    • Keep regex simple and understandable. 
    • Always integrate an actionable, helpful title message.
    • The pattern must be combined with backend validation. 
    • To check its consistent behaviour, test it across browsers. 

    When Should You Use pattern?

    The pattern attribute is majorly recommended in these cases: 

    • When you want to reduce invalid form entries.
    • When you want only accurate data to enter. 
    • When you want to deliver a seamless user experience. 
    • When you don’t want to majorly rely on JavaScript for simple validations.

    Certainly, the pattern attribute provides a minimalistic, clean, and efficient validation layer for login forms, sign-up pages, contact forms, and CRM data entry.

    Conclusion

    The HTML5 pattern attribute is an efficient, simple, and effective way to integrate input rules for validation at the browser level. When it is flawlessly implemented, the collected data from that form becomes more usable with the least anomalies and errors.

    admin

    Explore expert articles and resources designed to help businesses leverage technology for success and innovation.

    About Author

    admin

    Explore expert articles and resources designed to help businesses leverage technology for success and innovation.

    All Recent Posts