HTML Form Validation with required and pattern

HTML form validation helps you catch missing or incorrectly formatted input before a form is submitted. In this article, you’ll learn how the required and pattern attributes work, when to use them, and how to make them accessible and reliable.

Quick answer: Use required to make a field mandatory, and use pattern to enforce a format with a regular expression. Browsers handle the validation automatically when the form is submitted, as long as the field supports constraint validation.

Difficulty: Beginner

You'll understand this better if you know: basic HTML forms, common input elements like input and form, and the idea that browsers can validate user input before sending it.

1. What Is HTML Form Validation?

HTML form validation is the browser’s built-in way of checking whether form fields meet certain rules before submission. For the required and pattern attributes, the browser can block submission and show a validation message when a field is empty or does not match the expected format.

These attributes are part of HTML’s constraint validation system, which lets you add useful checks without writing JavaScript.

2. Why Form Validation Matters

Validation improves data quality, reduces user mistakes, and helps people fix problems before they submit a form. It also saves server work because obvious errors can be caught earlier in the browser.

For example, a signup form is easier to use when a missing email address or invalid postal code is flagged immediately. This makes the form feel faster and more helpful.

However, browser validation is not a security boundary. Server-side validation is still required, because users can bypass client-side checks.

3. Basic Syntax or Core Idea

The simplest form validation setup adds required to mandatory fields and pattern to fields with a specific format.

Minimal example

This example shows a required name field and a phone field that must match a simple digit-based format.

<form action="/submit" method="post">
  <label for="full-name">Full name</label>
  <input type="text" id="full-name" name="fullName" required>

  <label for="phone">Phone number</label>
  <input type="tel" id="phone" name="phone" pattern="[0-9]{10}" title="Enter a 10-digit phone number">

  <button type="submit">Submit</button>
</form>

The required attribute makes the name field mandatory. The pattern attribute checks the phone number against the regular expression [0-9]{10}, which means exactly 10 digits.

How the browser evaluates the field

When the user submits the form, the browser checks each field that participates in constraint validation. If a field is empty and marked required, or if its value does not match pattern, submission is blocked and the browser shows an error message.

4. Step-by-Step Examples

Example 1: Required email field

This example shows a common sign-up field that must not be left blank.

<form action="/subscribe" method="post">
  <label for="email">Email address</label>
  <input type="email" id="email" name="email" required>
  <button type="submit">Join</button>
</form>

Here, the browser will not let the form submit until the user enters a value. Because the input type is email, the browser may also validate that the text looks like an email address.

Example 2: Pattern for a postal code

A postal code often has a fixed format. You can use pattern to describe that format without JavaScript.

<label for="postal-code">Postal code</label>
<input type="text" id="postal-code" name="postalCode" pattern="[0-9]{5}" title="Enter a 5-digit postal code">

This pattern accepts exactly five digits. If the user types fewer or more digits, the browser considers the value invalid.

Example 3: Password with length and character rules

Patterns can describe more complex rules, such as a password that must contain at least one letter and one number.

<label for="password">Password</label>
<input type="password" id="password" name="password" required pattern="(?=.*[A-Za-z])(?=.*\d).{8,}" title="At least 8 characters, with letters and numbers">

This example uses a regular expression that requires at least one letter, at least one digit, and a minimum length of eight characters. The title attribute gives users a clearer hint about the expected format.

Example 4: Optional field with a format rule

Not every field needs to be required. You can apply pattern to an optional field, and the browser will only validate it if the user enters something.

<label for="extension">Phone extension</label>
<input type="text" id="extension" name="extension" pattern="[0-9]{1,5}" title="Enter 1 to 5 digits">

Because the field is not required, an empty value is allowed. If the user types an extension, it must match the digit-only pattern.

5. Practical Use Cases

These attributes are especially useful when the rules are simple and can be expressed directly in HTML.

6. Common Mistakes

Mistake 1: Using pattern without a clear text hint

Users need to know what format the browser expects. A pattern check without guidance often feels mysterious when the form refuses to submit.

Problem: The field is technically valid only for one exact format, but the user cannot tell what that format is from the interface.

<label for="code">Code</label>
<input type="text" id="code" name="code" pattern="[A-Z]{3}-[0-9]{3}">

Fix: Add a helpful title, and make the visible label more descriptive.

<label for="code">Discount code (format: ABC-123)</label>
<input type="text" id="code" name="code" pattern="[A-Z]{3}-[0-9]{3}" title=Enter a code like ABC-123>

The corrected version works better because it tells the user what a valid value looks like before submission fails.

Mistake 2: Expecting pattern to validate every input type the same way

The pattern attribute is only meaningful on inputs that support it. It is not a universal rule for all elements and all input types.

Problem: Applying a pattern to the wrong control can make the validation behave unexpectedly or not help at all.

<label for="birthday">Birthday</label>
<input type="date" id="birthday" name="birthday" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}">

Fix: Use the input type’s built-in behavior for dates, or switch to type="text" only if you truly need a custom format check.

<label for="birthday">Birthday</label>
<input type="date" id="birthday" name="birthday">

The corrected version relies on the native date control, which is usually more accessible and consistent than forcing a text pattern.

Mistake 3: Making a field required when optional submission is acceptable

Sometimes developers add required too aggressively. That can block valid submissions and frustrate users.

Problem: The browser will prevent submission if the field is empty, even when the business rule says the value is optional.

<label for="company">Company name</label>
<input type="text" id="company" name="company" required>

Fix: Remove required if the field is truly optional, and validate only when the value exists.

<label for="company">Company name (optional)</label>
<input type="text" id="company" name="company">

The corrected version works because the browser no longer treats an empty value as an error.

7. Best Practices

Use semantic labels and clear instructions

A good label helps both sighted users and screen reader users understand what the field expects. Validation messages are more effective when the field name is already clear.

<label for="member-id">Member ID</label>
<input type="text" id="member-id" name="memberId" required pattern="M-[0-9]{6}" title=Enter a member ID like M-123456>

This approach helps users understand the rule before they run into an error.

Choose patterns that are as simple as possible

Patterns should describe the real requirement, not every imaginable edge case. Overly complex regular expressions are hard to maintain and hard for users to satisfy.

<input type="text" name="sku" pattern="[A-Z]{3}[0-9]{4}" title=Enter 3 letters followed by 4 digits>

A simpler rule is easier to document, test, and explain to users.

Pair browser validation with server-side checks

Client-side validation improves user experience, but the server must still verify submitted data. This protects your application if the browser validation is bypassed or unsupported.

<form action="/account" method="post">
  <input type="text" name="accountNumber" required pattern="[0-9]{12}">
  <button type="submit">Save</button>
</form>

The browser catches obvious mistakes early, while the server remains the final authority.

8. Limitations and Edge Cases

One especially important detail is that pattern applies to the whole input value, so if you want to allow optional prefixes or suffixes, you must include them in the pattern itself.

9. Practical Mini Project

Let’s build a small newsletter signup form with one required field and one patterned field. The form uses semantic markup, clear labels, and hints that match the browser validation rules.

<form action="/newsletter-signup" method="post">
  <fieldset>
    <legend>Newsletter signup</legend>

    <label for="name">Name</label>
    <input type="text" id="name" name="name" required>

    <label for="subscriber-code">Subscriber code</label>
    <input type="text" id="subscriber-code" name="subscriberCode" pattern="SUB-[0-9]{4}" title=Enter a code like SUB-1234>

    <button type="submit">Sign up</button>
  </fieldset>
</form>

This form ensures the name is entered and the subscriber code follows the expected format. The fieldset and legend also make the form easier to understand for assistive technologies.

10. Key Points

11. Practice Exercise

Expected output: The form should refuse submission if the name is empty. It should also refuse an employee ID that does not match the pattern, but it should allow the field to remain blank.

Hint: Use required only on the name field, and use pattern plus title on the employee ID field.

<form action="/contact" method="post">
  <label for="full-name">Full name</label>
  <input type="text" id="full-name" name="fullName" required>

  <label for="employee-id">Employee ID (optional)</label>
  <input type="text" id="employee-id" name="employeeId" pattern="EMP-[0-9]{5}" title=Enter an ID like EMP-12345>

  <button type="submit">Send</button>
</form>

This solution works because the browser handles both the mandatory field and the optional format rule without needing extra scripting.

12. Final Summary

HTML form validation with required and pattern gives you a simple, native way to stop incomplete or incorrectly formatted submissions. It is a strong first line of defense for forms because the browser can validate values immediately and guide users toward correction.

At the same time, these attributes work best when paired with clear labels, helpful instructions, and server-side validation. Use required for values that must always be present, and use pattern when the text must follow a specific format.

If you want to go further, the next topic to study is the rest of HTML’s constraint validation features, including min, max, maxlength, and the browser validation states that control how invalid fields are presented.