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
Release: 2024-12-22 21:55:10
Original
909 people have browsed it

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();">
Copy after login

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();">
Copy after login

In this script:

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

  alert("Validation passed!");
  return true;
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template