innowqhy innowqhy - 2 years ago 66
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">
<button onclick="validateID()" type="submit" name="submit" class="btn">Submit</button>

And this is the JS,

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= "";

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= "";
it works.

I appreciate any help.

Answer Source

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


<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>


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download