Imagine you have a form on your website, and users keep submitting it with empty fields or garbage data. That is frustrating, right? HTML gives you a set of built-in validation attributes that let you catch bad input before it ever reaches your server. No JavaScript required for the basics.
The Required Attribute
The simplest validation tool in your kit is the required attribute. Stick it on any input, and the browser will refuse to submit the form if that field is empty. It works on text fields, emails, passwords, checkboxes, selects, and textareas.
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<button type="submit">Sign Up</button>
</form>
Minlength and Maxlength
Want to make sure a password is at least 8 characters? Or cap a username at 20 characters? minlength and maxlength do exactly that. The browser will show a helpful error message if the user types too little or too much.
<input type="password" name="password" minlength="8" maxlength="32" required>
<input type="text" name="username" minlength="3" maxlength="20" required>
Min and Max for Numbers
For number inputs and date inputs, you can set min and max to define the allowed range. The browser will reject values outside this range and even provide handy up/down arrows that stay within bounds.
<input type="number" name="age" min="13" max="120" required>
<input type="date" name="birthday" min="1900-01-01" max="2010-12-31">
The Pattern Attribute
The pattern attribute lets you define a regular expression that the input value must match. This is incredibly powerful for things like phone numbers, postal codes, or any custom format you need.
<input type="text" name="zipcode" pattern="[0-9]{5}" title="Five digit zip code" required>
<input type="text" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" title="Format: 123-456-7890">