1

formValidation() function return false but not preventing form submission

<body>
    <script>
        function formValidation(){
            return false;
        }
    </script>
    <form onsubmit="formValidation()" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
        <label for="email">Email:</label><br>
        <input type="email" name="email" id="email"><br><br>
        <input type="submit" name="submit" value="submit">
    </form>
</body>

When i have used return front of formValidation() function it is working

<body>
    <script>
        function formValidation(){
            return false;
        }
    </script>
    <form onsubmit="return formValidation()" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
        <label for="email">Email:</label><br>
        <input type="email" name="email" id="email"><br><br>
        <input type="submit" name="submit" value="submit">
    </form>
</body>
abu raihan
  • 11
  • 1
  • i presume that event attribs turn into event handlers like `function(event){with(this){[attr]}}`, so the `return` sets a return value in that anon function. – dandavis Apr 11 '22 at 03:09

1 Answers1

0

Inline handlers like these essentially turn into a function body. Said function is executed when the event is fired.

function theHandler() {
  // Attribute string goes here
}

If the function returns false, the event's default action (such as submitting the form) is prevented.

<form onsubmit="formValidation()"

doesn't work because then the constructed function that gets executed doesn't return anything:

function theHandler() {
  formValidation()
}

But

<form onsubmit="return formValidation()"

works because then the constructed function is like

function theHandler() {
  return formValidation()
}

It's somewhat confusing - and is one of the (many) reasons why you should never use inline handlers. Attach the event listener properly using JavaScript instead.

document.querySelector('form').addEventListener('submit', formValidation);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320