To require two form fields to match in HTML5 with JavaScript, you can use the pattern
attribute along with a regular expression to validate both fields.
For example we write:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Matching Form Fields with HTML5 and JavaScript</title>
</head>
<body>
<form id="myForm">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<label for="confirmPassword">Confirm Password:</label>
<input type="password" id="confirmPassword" name="confirmPassword" required>
<input type="submit" value="Submit">
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
var password = document.getElementById("password").value;
var confirmPassword = document.getElementById("confirmPassword").value;
if (password !== confirmPassword) {
alert("Passwords do not match!");
event.preventDefault(); // Prevent form submission
}
});
</script>
</body>
</html>
In this example, the JavaScript code adds an event listener to the form’s submit event. When the form is submitted, it retrieves the values of the password and confirm password fields.
If the two values do not match, an alert is displayed, and event.preventDefault()
is called to prevent the form from being submitted.
Additionally, you can use the pattern
attribute along with a regular expression directly in the HTML to enforce a specific pattern for the fields.
For example, if you want to require that the password contains at least one uppercase letter, one lowercase letter, and one digit, you can use a pattern like this:
<input type="password" id="password" name="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" required>
This pattern requires the password to be at least 8 characters long and contain at least one digit, one lowercase letter, and one uppercase letter.