Zac Charles
Zac Charles

Reputation: 3

Struggling with jQuery form validation

I am creating a very simple register form with only two inputs and submit button.
The problem I am having is that it will only complete one if statement.

Here is the jQuery I made:

$("#usernameError").hide();
$("#passwordError").hide();

$("#registrationSubmit").click(function(){

  if($("#username").val() == ""){

    $("#usernameError").show();
    return false;
  }

  if($("#passwordReg").val() == ""){

    $("#passwordError").show();
    return false;
  }
});

And here is the HTML using bootstrap:

<div class="modal fade" id="add-admin-modal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header admin">
         Please Enter Details
      </div>
      <div class="modal-body admin">
        <form id="registrationForm" action="registerAction.php" method="post">
          <div class="form-group">
            <label for="">Username</label>
            <input name="username" type="username" class="form-control" id="username" aria-describedby="emailHelp" placeholder="Enter Username">
            <div id="usernameError" class="alert alert-danger pad" role="alert">A Username is required!</div>
          </div>
          <div class="form-group">
            <label for="password">Password</label>
            <input name="password" type="password" class="form-control" id="passwordReg" placeholder="Password">
            <div id="passwordError" class="alert alert-danger pad" role="alert">A Password is required!</div>
          </div>

          <div class="form-group">
            <button type="submit" id="registrationSubmit" name="registrationSubmit" class="btn btn-success">Ok</button>
            <button class="btn btn-default" data-dismiss="modal">Cancel</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
<script src="validations.js"></script>

The script will validate the username and show the error, but doesn't do anything with the password.

Is it because I am using return false to prevent the form for submiting?
What can I use instead?

Upvotes: 0

Views: 56

Answers (2)

lloyd
lloyd

Reputation: 1181

You are returning out of your code. Don't do that if you want to execute code after

var ValidationFailed = false;

if($("#username").val() == ""){

    $("#usernameError").show();
    ValidationFailed = true;
}

if($("#passwordReg").val() == ""){

    $("#passwordError").show();
    ValidationFailed = true;

}
//.....

return ValidationFailed;

Upvotes: 0

Killer Death
Killer Death

Reputation: 459

Yes, that is the reason, remove return statement. You can use a boolean variable errorOccurred and set it to true if there was an error. Somewhere you have a post function which will not post data if an error occurred.

Upvotes: 1

Related Questions