HTML5 – Form validation
Form validation is the process of checking that user input is correct and complete before it is submitted to the server. In HTML5, form validation can be performed using built-in form validation attributes and JavaScript.
Here is an example of a form with built-in form validation in HTML5:
<form action="/submit" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number, one uppercase and lowercase letter, and at least 8 or more characters" required><br>
<input type="submit" value="Submit">
</form>
In this example, the required
attribute is used to make the name and email fields required, and the pattern
attribute is used to specify a regular expression to validate the password field. The title
attribute is used to provide a description of the pattern to the user.
If the user tries to submit the form with invalid input, a message will be displayed to the user indicating the error.
You can also perform form validation using JavaScript. This can be useful for performing more complex validation or for handling server-side errors.
Here is an example of form validation using JavaScript:
<form action="/submit" method="post" onsubmit="return validateForm()">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number, one uppercase and lowercase letter, and at least 8 or more characters" required><br>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var name = document.forms["form"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["form"]["email"].value;
if (email == "") {
alert("Email must be filled out");
return false;
}
var password = document.forms["form"]["password"].value;
if (password == "") {
alert("Password must be filled out");
return false;
}
}
</script>
In this example, the validateForm()
function is called when the form is submitted. The function checks the value of each form field and displays an alert if the field is empty. The return false
statement prevents the form from being submitted if any of the fields are empty.
You can customize the form validation script to perform more complex validation, such as checking the length or format of the input. You can also display custom error messages to the user using the innerHTML
property of the form element.