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,
- 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?
- How does the execution continue till the line
return false
afterwindow.location.href
? Shouldn'twindow.location.href
direct to a new page stopping execution? The script does not work ifreturn false
is removed i.e. the unchecked form data is sent to xyz.php.