Skip to content

Web APIs (Forms & Storage)

1. Web Forms API

JavaScript can validate user input.

function validateForm() {
  let x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
}

Constraint Validation

HTML5 built-in validation attributes (like required, min, max) can be checked via JS.

if (!inputObj.checkValidity()) {
  document.getElementById("demo").innerHTML = inputObj.validationMessage;
}

2. Web Storage API

The Web Storage API provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies.

Local Storage

Stores data with no expiration date. The data will not be deleted when the browser is closed.

// Store
localStorage.setItem("lastname", "Smith");

// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

// Remove
localStorage.removeItem("lastname");

Session Storage

Stores data for one session (data is lost when the browser tab is closed).

sessionStorage.setItem("lastname", "Smith");

Security

Never store sensitive information (passwords, credit cards) in Local Storage because it is accessible by any script on the page (XSS vulnerability).