HTML5 introduced built-in form validation capabilities that simplify client-side validation without the need for JavaScript. You can use HTML5 attributes to enforce rules for user inputs.
required: Ensures that the input field must be filled out before submitting the form.
<input type="text" name="username" required>
minlength and maxlength: Sets the minimum and maximum length of the input value.
<input type="text" name="username" minlength="3" maxlength="10" required>
pattern: Specifies a regular expression that the input value must match.
<input type="text" name="username" pattern="[A-Za-z]{3,}" required>
type: Determines the type of data expected and provides built-in validation for common types like email, number, url, etc.
<input type="text" name="username" pattern="[A-Za-z]{3,}" required>
min and max: Define the range for numerical input or date values.
<input type="number" name="age" min="18" max="99" required>
<input type="date" name="birthday" min="1900-01-01" max="2024-12-31" required>
step: Defines the step size for numerical or date inputs.
<input type="number" name="quantity" step="0.01" min="0" required>
Example Form with HTML5 Validation
Here’s an example form demonstrating several of these attributes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML5 Form Validation</title>
</head>
<body>
<form action="/submit" method="post">
<label for="username">Username (3-10 letters):</label>
<input type="text" id="username" name="username" minlength="3" maxlength="10" pattern="[A-Za-z]{3,10}" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="age">Age (18-99):</label>
<input type="number" id="age" name="age" min="18" max="99" required>
<br><br>
<label for="dateOfBirth">Date of Birth:</label>
<input type="date" id="dateOfBirth" name="dateOfBirth" min="1900-01-01" max="2024-12-31" required>
<br><br>
<label for="quantity">Quantity (Step of 0.01):</label>
<input type="number" id="quantity" name="quantity" step="0.01" min="0" required>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
How It Works
- Required Fields: If a field marked
requiredis left empty, the form will not submit, and the browser will prompt the user to fill it out. - Pattern Matching: The
patternattribute uses a regular expression to validate the input format. - Min/Max/Step: For numeric inputs,
min,max, andsteprestrict the range and granularity of input values. - Type-Specific Validation: Input types like
email,number, anddateautomatically validate input format.
HTML5 Form Validation With the “pattern” Attribute
The pattern attribute in HTML5 is used to specify a regular expression (regex) that the value of an input field must match in order to be considered valid. This can be particularly useful for enforcing specific formats for text input fields, such as phone numbers, zip codes, or custom validation rules.
How to Use the pattern Attribute
<form>
<label for="username">Username (letters only, 3-10 characters):</label>
<input type="text" id="username" name="username" pattern="[A-Za-z]{3,10}" title="Username must be 3-10 letters long and contain only letters." required>
<br><br>
<label for="phone">Phone Number (10-digit number):</label>
<input type="tel" id="phone" name="phone" pattern="\d{10}" title="Phone number must be 10 digits long, without any dashes or spaces.">
<br><br>
<label for="zipcode">ZIP Code (5 digits or 5+4 digits):</label>
<input type="text" id="zipcode" name="zipcode" pattern="\d{5}(-\d{4})?" title="ZIP Code must be either 5 digits or 5 digits followed by a hyphen and 4 more digits.">
<br><br>
<input type="submit" value="Submit">
</form>
Explanation of the Regex Patterns
[A-Za-z]{3,10}: Matches a string containing only letters (both uppercase and lowercase), with a length between 3 and 10 characters.\d{10}: Matches exactly 10 digits.\drepresents a digit, and{10}specifies that there must be exactly 10 of them.\d{5}(-\d{4})?: Matches either 5 digits or 5 digits followed by a hyphen and 4 more digits. The(-\d{4})?part makes the hyphen and the following 4 digits optional.
Attributes Used with pattern
title: Provides a message that will be displayed if the input does not match the pattern. This message is used by the browser’s default validation behavior.required: Makes the field mandatory to fill out.
Custom Error Messages and Validation
The title attribute is used to specify the error message shown when the input does not match the pattern. Custom JavaScript can also be used for more sophisticated validation and error messaging.
Here’s an example of how to use JavaScript to provide custom validation feedback:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pattern Validation Example</title>
</head>
<body>
<form id="myForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" title="Please enter a valid email address.">
<br><br>
<label for="username">Username (alphanumeric, 4-12 characters):</label>
<input type="text" id="username" name="username" pattern="[a-zA-Z0-9]{4,12}" title="Username must be 4-12 alphanumeric characters.">
<br><br>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
const username = document.getElementById('username');
if (!username.checkValidity()) {
alert(username.title);
event.preventDefault(); // Prevent form submission
}
});
</script>
</body>
</html>
