0

I have a form in HTML page. It includes:

<form action="result.html" method="get" onsubmit="return validation()">

So even the ValidationEvent() returns false I can render the result.html. Below is the definition of the function:

// Below Function Executes On Form Submit
function validation() {
    // Storing Field Values In Variables
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var contact = document.getElementById("contact").value;
    // Regular Expression For Email
    var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;
    
    // Conditions
    if (name != '' && email != '' && contact != '') {
        if (emailReg.test(email)==true) {
            //  if (email.match(emailReg)) 
            if (document.getElementById("male").checked || document.getElementById("female").checked) {
                if (contact.length == 10) {
                    alert("All type of validation has done on OnSubmit event.");
                    console.log("All type of validation has done on OnSubmit event.")
                    return true;
                } 
                else {
                    alert("The Contact No. must be at least 10 digit long!");
                    console.log("The Contact No. must be at least 10 digit long!");
                    return false;
                }
            } 
            else {
                alert("You must select gender.....!");
                return false;
            }
        } 
        else {
            alert("Invalid Email Address...!!!");
            return false;
        }
    } 
    else {
        alert("All fields are required.....!");
        return false;
    }
}

my HTML page is:

<!DOCTYPE html>
<html>
<head>
    <title>Javascript Onsubmit Event Example</title>
    <link href="style.css" rel="stylesheet"> <!-- Include CSS File Here-->
    <script src="js/event.js"></script>
</head>
<body>
    <div class="container">
        <div class="main">
            <form action="result.html" method="get" onsubmit="return validation(e);">
                <h2>Javascript Onsubmit Event Example</h2>
                <label>Name :</label>
                <input id="name" name="name" placeholder="Name" type="text">
                <label>Email :</label>
                <input id="email" name="email" placeholder="Valid Email" type="text">
                <label>Gender :</label>
                <input id="male" name="gender" type="radio" value="Male">
                <label>Male</label>
                <input id="female" name="gender" type="radio" value="Female">
                <label>Female</label>
                <label>Contact No. :</label>
                <input id="contact" name="contact" placeholder="Contact No." type="text">
                <input type="submit" value="Submit">
                <span>All type of validation will execute on OnSubmit Event.</span>
            </form>
        </div>
    </div>
</body>
</html>

How can prevent the form to be submitted.

phentnil
  • 2,195
  • 2
  • 14
  • 22
alig
  • 15
  • 4
  • Inline event handlers like `onsubmit` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. See [How to prevent form from being submitted?](/q/3350247/4642212). Use `yourForm.addEventListener("submit", (event) => { event.preventDefault(); /* Perform validation. When ready to submit: */ event.target.submit(); });`. – Sebastian Simon Dec 05 '21 at 20:55
  • returning false outta do the trick - but if there's an error in your script it will submit anyways – Kinglish Dec 05 '21 at 20:57
  • 1
    The JS errors with "invalid range in character class" and if it didn't, then when you try to submit the form, the event handler will throw an exception because you haven't defined the `e` that you try to pass to `validation`. Your code **never reaches `return false`**. You need to provide a [mcve] that actually demonstrates the problem. – Quentin Mar 20 '22 at 21:22

1 Answers1

-1

Returning false will not prevent the form to be submitted either way. You should also call preventDefault to prevent the default form action for Ajax form submissions.

e.preventDefault();

The preventDefault() method of the Event interface actually tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be taken.

More about preventDefault() - https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
  • "Returning false will not prevent the form to be submitted either way" — It would if one of the `return false` lines was ever reached. It isn't considered best practise but it does work. – Quentin Mar 20 '22 at 21:22
  • -1 because of this is not true.. yes, it is recommended to use listeners and event.preventDefault. But returning from onsubmit is very valid way to prevent submitting. – Reloecc Aug 23 '23 at 18:11