Problem Statement
Which attribute uses regular expressions for validation?
Explanation
The pattern attribute uses regular expressions for validation. It allows you to specify a pattern that the input value must match. For example, pattern equals square bracket 0 hyphen 9 close bracket curly brace 3 close curly brace requires exactly three digits. The browser checks if the input matches the pattern before allowing submission. If it does not match, the browser shows an error message. Pattern validation is powerful for enforcing specific formats like phone numbers, zip codes, or custom formats. You can use the title attribute to provide a helpful message explaining the required format. Pattern only works with text-based input types like text, tel, email, url, password, and search. It is ignored for other types. Remember that pattern validation is client-side only and can be bypassed, so always validate on the server too.
Code Solution
SolutionRead Only
<!-- US phone number pattern -->
<form>
<label for="phone">Phone (XXX-XXX-XXXX):</label>
<input type="tel"
id="phone"
name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
title="Format: 123-456-7890"
required>
</form>
<!-- Zip code pattern -->
<form>
<label for="zip">ZIP Code:</label>
<input type="text"
id="zip"
name="zip"
pattern="[0-9]{5}"
title="5-digit ZIP code"
required>
</form>
<!-- Username pattern (letters and numbers only) -->
<form>
<label for="username">Username:</label>
<input type="text"
id="username"
name="username"
pattern="[A-Za-z0-9]+"
title="Only letters and numbers allowed"
minlength="3"
required>
</form>
<!-- Custom format pattern -->
<form>
<label for="code">Product Code (ABC-123):</label>
<input type="text"
id="code"
name="code"
pattern="[A-Z]{3}-[0-9]{3}"
title="Format: ABC-123"
required>
</form>