1

I have the following validation script that works fine, but I don't understand how it works and need your help with it.

The HTML,

<form action="xyz.php" method="post">
    <div class="form-group">
        <label class="sr-only" for="id">Enter ID</label>
        <input type="text" class="form-control" name="id" id="id" required>
    </div>
    <button onclick="return validateID()" type="submit" name="submit" class="btn">Submit</button>
</form>

And this is the JS,

<script>
function validateID() {
    var id = document.getElementById("id").value;
    var regL= new RegExp("^([0-9][0-9][0-9])$");

    if (!( (regL.test(id)) )) {
        window.location.href = "index-iderror.php";
        return false;
    } else {
        return true;
    }
}
</script>

Some questions that I have about this,

  1. What happens when false or true is returned to onclick? Does it decide whether the form data is or is not sent to xyz.php?
  2. How does the execution continue till the line return false after window.location.href? Shouldn't window.location.href direct to a new page stopping execution? The script does not work if return false is removed i.e. the unchecked form data is sent to xyz.php.
innowqhy
  • 53
  • 8
  • 1) http://stackoverflow.com/questions/128923/whats-the-effect-of-adding-return-false-to-an-click-event-listener – Thernys May 05 '16 at 05:55
  • 2) http://stackoverflow.com/questions/2536793/does-changing-window-location-stop-execution-of-javascript – Thernys May 05 '16 at 06:04
  • 2) or http://stackoverflow.com/questions/10525584/what-happens-to-code-after-a-javascript-redirect-setting-window-location-href or many other google results – Thernys May 05 '16 at 06:12
  • The listener should be on the form, not the submit button as the form can be submitted without clicking the button and the validation will not run. Also, no form element should have a name of "submit", as it replaces the form's submit method so it can't be called. – RobG May 05 '16 at 06:14

0 Answers0