Home >Web Front-end >JS Tutorial >How Can JavaScript Prevent Form Submission and Redirect to the Previous Page on Validation Failure?

How Can JavaScript Prevent Form Submission and Redirect to the Previous Page on Validation Failure?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-22 21:55:10902browse

How Can JavaScript Prevent Form Submission and Redirect to the Previous Page on Validation Failure?

Preventing Form Submission in JavaScript

Question:

In a JavaScript form validation scenario, how can you prevent form submission and return to the previous page when a certain condition is met?

Answer:

There are several approaches to resolve this issue:

Method 1: Using preventDefault() and a Validation Function

<form onsubmit="event.preventDefault(); validateMyForm();">

In this method, validateMyForm() should return false if the validation fails.

Method 2: Returning a Value from the Validation Function

<form name="myForm" onsubmit="return validateMyForm();">

In this script:

function validateMyForm() {
  if (condition fails) {
    alert("Validation failed!");
    returnToPreviousPage();
    return false;
  }

  alert("Validation passed!");
  return true;
}

Method 3: Setting the returnValue Property (Needed for Chrome 27.0.1453.116 m)

function validateMyForm() {
  if (condition fails) {
    alert("Validation failed!");
    returnToPreviousPage();
    event.preventDefault();
    event.returnValue = false; // Set `returnValue` to false
  }

  alert("Validation passed!");
  return true;
}

The above is the detailed content of How Can JavaScript Prevent Form Submission and Redirect to the Previous Page on Validation Failure?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn