How is the pattern attribute used in HTML forms?

QuestionsQuestions8 SkillsProShake on Invalid InputOct, 29 2025
0110

The pattern attribute in HTML forms is used to specify a regular expression that the input field's value must match for the form to be submitted. It is commonly used with <input> elements to enforce specific formats for user input, such as phone numbers, email addresses, or custom formats.

Here’s an example of how to use the pattern attribute:

<form>
  <label for="phone">Phone Number:</label>
  <input type="text" id="phone" name="phone" pattern="\d{3}-\d{3}-\d{4}" required>
  <small>Format: 123-456-7890</small>
  <input type="submit" value="Submit">
</form>

In this example:

  • The pattern attribute specifies that the phone number must be in the format 123-456-7890, where \d represents a digit and {n} indicates the number of digits required.
  • The required attribute ensures that the field must be filled out before submission.

If the user enters a value that does not match the specified pattern, the form will not submit, and the browser will typically display a validation message.

0 Comments

no data
Be the first to share your comment!