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
patternattribute specifies that the phone number must be in the format123-456-7890, where\drepresents a digit and{n}indicates the number of digits required. - The
requiredattribute 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.
