Home > other >  How to override form validation using JavaScript
How to override form validation using JavaScript

Time:09-17

How do I write a function that overrides form validation when a user clicks the back button?

If the user doesn't fill the form and clicks submit, it tells shows " please fill in this field" then I added a back button in case the user doesn't wanna fill the form and wants to go back but onClick it shows "please fill in this field"

how do I override this when the user clicks back?

function validateForm() {
  var x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
}

function goBack() {
  window.history.back()
}
<div class="form-div">
  <form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post" required>
    <button onclick="goBack()">Go Back</button>
    <div class="container">
      <h1>Register</h1>
      <p>Please fill in this form to create an account.</p>
      <hr>
      <label for="name"><b>FullName</b></label>
      <i class="fa fa-user icon"></i>
      <input type="text" placeholder="Enter Name" name="fullName" id="name" required>
      <label for="email"><b>Email</b></label>
      <i class="fa fa-envelope icon"></i>
      <input type="text" placeholder="Enter Email" name="email" id="email" required>
      <label for="psw"><b>Password</b></label>
      <i class="fa fa-key icon"></i>
      <input type="password" placeholder="Password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required>
      <label for="psw-repeat"><b>Repeat Password</b></label>
      <i class="fa fa-key icon"></i>
      <input type="password" placeholder="Repeat Password" name="psw-repeat" id="psw-repeat" required>
      <p>By creating an account you agree to our <a href="#">Terms & Privacy</a>.</p>
      <button type="submit" class="registerbtn">Register</button>
    </div>
    <div class="container signin">
      <p>Already have an account? <a href="#">Sign in</a>.</p>
    </div>
  </form>
</div>

CodePudding user response:

I think removing the "required" attribute from your form tag should be good even if you keep this "required" attribute on your inputs.

CodePudding user response:

This thing happen because you added button inside <form> that causing it to act as a submit button
see this: How to prevent buttons from submitting forms

so basically you can return false, but its much easer to just remove the button outside the <form>

FYI
You should ALWAYS check the values of the inputs buy yourself because everyone who is familiar with the devTools can delete the required attribute and then send empty values to your server

Another FYI
You must check the values also in the server because there are many ways you can override the client checks (you do the client side check just for UX)

  • Related