Home >Web Front-end >JS Tutorial >How Can JavaScript Prevent Form Submission and Redirect to the Previous Page on Validation Failure?
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!