Form Validation with Events
Checking input before submission using focus(), select() and return false.
Checking Form Input with JavaScript
JavaScript validation catches errors before data is sent to the server.
Steps for form validation
- Detect the error and display an alert message.
- Put the invalid element in focus using
focus(). - Highlight the text using
select(). return falseto prevent form submission.
// Put focus on the phone field
document.getElementById("phone").focus();
// Highlight / select the field text
document.getElementById("phone").select();
Example: Comparing Passwords
Ask the user to enter their password twice and verify they match. The handler is triggered by the form's onsubmit event.
function validatePasswords() {
var p1 = document.getElementById("pass1").value;
var p2 = document.getElementById("pass2").value;
if (p1 === "") {
document.getElementById("pass1").focus();
return false;
}
if (p1 !== p2) {
document.getElementById("pass1").focus();
document.getElementById("pass1").select();
alert("Passwords do not match!");
return false;
}
return true;
}
<form onsubmit="return validatePasswords();">
Password: <input type="password" id="pass1"><br>
Confirm: <input type="password" id="pass2"><br>
<input type="submit" value="Submit">
</form>
Activity — complete the code
Complete the code correctly to mark this lesson as complete automatically.
Complete the password validation function.
function validate() {var p1 = document.getElementById("pass1").;var p2 = document.getElementById("pass2").value;if (p1 !== p2) {document.getElementById("pass1").(); // put focus on the fielddocument.getElementById("pass1").(); // highlight the textalert("Passwords do not match!");return ; // prevent submission}return true;}