Form validation ensures that the data submitted by users meets certain rules before it is sent to the server.
HTML5 introduced built-in form validation attributes, making it easier to validate user input without JavaScript (though JS can be used for advanced validation).
Use the required attribute to make a field mandatory.
<label for="username">Username:</label> <input type="text" id="username" name="username" required>
Some input types automatically validate user input:
<label for="email">Email:</label> <input type="email" id="email" name="email" required>
abc → browser shows an errorabc@example.comUse minlength and maxlength attributes:
<label for="password">Password:</label> <input type="password" id="password" name="password" minlength="6" maxlength="12" required>
The pattern attribute allows custom rules:
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{10}" required>
Example for password with at least 1 uppercase, 1 lowercase, 1 number, 6–12 chars:
<input type="password" name="password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,12}"
title="6-12 chars, at least 1 uppercase, 1 lowercase, 1 number"
required>
Use min and max attributes:
<label for="age">Age:</label> <input type="number" id="age" name="age" min="18" max="60" required>
For dates:
<label for="dob">Date of Birth:</label> <input type="date" id="dob" name="dob" min="2000-01-01" max="2025-12-31">
Use title to provide custom instructions:
<input type="text" name="username" required pattern="[A-Za-z]{3,10}" title="3-10 letters only">
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HTML Form Validation Practice</title>
<style>
form {
width: 400px;
margin: 20px auto;
font-family: Arial, sans-serif;
}
label {
display: block;
margin: 10px 0 5px;
}
input, select, textarea {
width: 100%;
padding: 8px;
margin-bottom: 10px;
}
input[type="submit"] {
width: auto;
background-color: #2c3e50;
color: white;
border: none;
cursor: pointer;
padding: 10px 20px;
}
input[type="submit"]:hover {
background-color: #1abc9c;
}
</style>
</head>
<body>
<h1>Registration Form with Validation</h1>
<form action="/submit.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required minlength="3" maxlength="15" title="3-15 characters">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,12}"
title="6-12 chars, include uppercase, lowercase, number">
<label for="age">Age:</label>
<input type="number" id="age" name="age" required min="18" max="60">
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" required pattern="[0-9]{10}" title="10 digits only">
<input type="submit" value="Register">
</form>
</body>
</html>