Client-side validation is the process of checking user input directly in the user’s browser, providing instant feedback and preventing unnecessary submissions of incorrect data to the server. While convenient, it must not be relied upon for security, as users can bypass browser validation. Server-side validation is always required for security.
1. The required Attribute
The simplest and most important validation attribute is required.
- Purpose: Ensures the user must enter a value into the field before the form can be submitted. If left empty, the browser will display a default error message and prevent submission.
- Syntax: It is a boolean attribute (its presence enables the feature).
<label for="name">Your Name:</label>
<input type="text" id="name" name="user_name" required>
2. Length Constraints (minlength and maxlength)
These attributes control the minimum and maximum number of characters allowed in a text field.
| Attribute | Purpose |
minlength | Specifies the minimum required number of characters. |
maxlength | Specifies the maximum allowed number of characters. |
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="password" minlength="8" maxlength="20" required>
3. Range and Step Constraints (min, max, and step)
These are used primarily with numerical input types (type="number", type="range", type="date", etc.) to constrain the accepted range of values.
| Attribute | Purpose |
min | The minimum allowable value. |
max | The maximum allowable value. |
step | The interval between legal numbers (e.g., step="5" means only 5, 10, 15, etc., are valid). |
<label for="qty">Quantity (1-10):</label>
<input type="number" id="qty" name="quantity" min="1" max="10" value="1">
4. Built-in Type Validation
HTML5 introduced specialized input types that automatically check for basic format correctness:
type="email": Checks if the input contains text followed by@followed by a domain (e.g.,a@b.com).type="url": Checks if the input starts with a valid protocol likehttp://orhttps://.
<label for="email">Email:</label>
<input type="email" id="email" name="user_email" required>
5. Custom Validation with pattern
For complex validation rules, you can use the pattern attribute, which takes a Regular Expression (RegEx) as its value. The browser checks if the user’s input matches the defined pattern.
<input type="text"
name="zip_code"
pattern="\d{5}"
title="A 5-digit ZIP code (e.g., 90210)"
required>
Tip: Always use the
titleattribute withpattern. If the validation fails, the browser displays thetitletext as a helpful hint to the user.
6. Bypassing Validation (formnovalidate)
The formnovalidate attribute is a boolean attribute that can be placed on the submit button. When this specific button is clicked, it forces the form to submit its data without running any client-side validation checks.
<button type="submit">Submit and Validate</button>
<button type="submit" formnovalidate>Save Draft (Skip Check)</button>
