Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 6

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

  1. Detect the error and display an alert message.
  2. Put the invalid element in focus using focus().
  3. Highlight the text using select().
  4. return false to 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 field
document.getElementById("pass1").(); // highlight the text
alert("Passwords do not match!");
return ; // prevent submission
}
return true;
}