Ian Davis
Ian Davis

Reputation: 19423

html5 validate form with required="true" and custom check

What I'm looking for: way to have innate html 5 form validation using the required="true", where if the user clicks the "Submit" button, the first thing that happens is the automatic html 5 validation where it checks to see if "username" is provided by the user. If it's not, then it displays the ugly error bubble.

If it is provided, however, I then have my own custom validation for checking against the db if the username exists. If it does, then return true (allow submission), false otherwise. What's happening: the form is getting submitted. It's like it does not wait for the success callback to return true/false on whether or not it should be submitted.

I hope that's clear enough! Code below:

html:

<form>
<input type="text" required="true" id="username" />
<button type="submit">Submit</button>
</form>

js:

$("form").submit(function() {
  $.ajax({
      url: 'usernamechecker.php?username=' + $("#username").val(),
      success: function(resp) {
        if (!resp.UsernameExists) {
          return true; // allow form submission
        }
        return false; // do not allow form submission
      }
    });
});

Upvotes: 1

Views: 2406

Answers (2)

Cory Danielson
Cory Danielson

Reputation: 14501

You need to add "async: false" as a parameter to your ajax call in order to force the call to finish before continuing on with the rest of the code.

$("form").submit(function(event) {
  $.ajax({
      async: false,
      url: 'usernamechecker.php?username=' + $("#username").val(),
      timeout: 1000,
      success: function(resp) {
        if (resp.UsernameExists) {
          event.preventDefault(); // do not allow form submission
        },
      error: function() {
          //fall back code when there's an error or timeout
      },
    });
});

Upvotes: 0

Pointy
Pointy

Reputation: 413757

You can't return a value through a callback like that. The callback for "success" won't run until the "ajax" call has completed, long after the "submit" handler has already returned.

Instead of that, I'd just do the submit and let it return with an error if there are server-side issues (like "username in use" or whatever). There's no point making two round-trips. If there are no problems, it can just complete the operation and return whatever results page you want.

Upvotes: 1

Related Questions