innowqhy innowqhy - 7 months ago 12
Javascript Question

Redirect users when validation fails

I am facing some problem validating my form using JS.

This is the HTML,

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


And this is the JS,

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

if (!(reg1.test(id))) {
document.location.href= "http://www.errorpage.com";
}
}
</script>


It is supposed to check the submitted form value against the regex and if the validation fails it has to redirect to an error page.

However, it doesn't redirect. When I put an alert() in place of
document.location.href= "http://www.errorpage.com";
it works.

I appreciate any help.

Answer

i think its not about location.href. its because the button type is submit and form do the default thing and submit the form to xyz.php. thats why when he put alert(). it works

Change

<button onclick="validateID()" type="submit" name="submit" class="btn">Submit</button>

to type button

<button onclick="validateID()" type="button" name="submit" class="btn">Submit</button>

or

use onsubmit="validateID()" in form tag and remove on click event from button