innowqhy
innowqhy

Reputation: 53

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.

Upvotes: 1

Views: 85

Answers (3)

Nezir
Nezir

Reputation: 6915

<html>
<head>
<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";
        return true;
    }else{

          return false;
    }
  }
</script>
</head>
<body>
<form action="xyz.php" method="post" onsubmit="event.preventDefault();  validateID();">
  <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  type="submit" name="submit" class="btn">Submit</button>
</form>
</body>
</html>

Upvotes: 0

Syed Ekram Uddin
Syed Ekram Uddin

Reputation: 3091

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

Upvotes: 2

witchy
witchy

Reputation: 26

Try window.location.href or location.href

The detailed reason: What is the difference between document.location.href and document.location?

Upvotes: 1

Related Questions