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

Form Validation with Events

4 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 6 deck

Form Validation with Events
Fullscreen for presentation · Print / PDF for a handout
1 / 4
Lesson

Form Validation with Events

Checking input before submission using focus(), select() and return false.

Form Validation with Events

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();
Form Validation with Events

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>
Form Validation with Events

Activity — complete the code

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;
}