2

I'm using the Jquery Validation plugin to validate my form on the client before submitting.

There is a specific field in my form that I want to validate using ajax to the server, once the user has filled out that field (onblur). (Basically it's the username field, I want to check on the server if the username is available and show a message accordingly)

Here is the code I'm using to validate my form:

$(document).ready(function()
{
     $("#signupForm").validate({
        submitHandler: ajaxSubmitForm});

});

(ajaxSubmitForm is just the js code that submits the form)

How can I use the Jquery Validation plugin to have the username field send its value to the server (using ajax) when it has changed and have the server return a result that somehow marks that field as valid on the client so the rest of the validation works?

Thanks

2 Answers 2

2

You can do this using the remote rule on that element. You'd apply like so:

$('#signupForm').validate({
    rules: {
        username: {
            remote: 'check_username.php' // this is the service page that returns true/false
        }
    }
});

Then to trigger the validation on blur, you add the following:

$('input[name="username"]').on('blur', function() {
    $('#signupForm').validate().element(this); // this triggers the single element validation
});
Sign up to request clarification or add additional context in comments.

5 Comments

Ugh, that is SO much easier. Learn something new everyday
Awesome, very elegant solution. Any idea how the server can return a message too and not just true/false? Would be great to be able to get the result (true/false) and a reason from the server and then access it on the client.
Well ideally each validation rule has its own test/message, so you'd only want to use this service to verify if the username is taken. If you need to match it for acceptable characters, that would be a different rule that you would handle client-side. What are the additional use cases? I'd be happy to talk you through setting up those rules. You should accept this answer, however, as it answers the question as initially stated.
Ideally, I'd like to have 1 place that handles all the logic for validating the username, and since I have to make a server request to check availability, it should be there. So I'd like the server to return whether the username is taken or if it's too short, for example. I know I can work around with client side validation for the length but that means my validation logic is separated.
I think you're looking at it the wrong way; you still have to call the validation client side, and you're still defining the rule for uniqueness on the client side, you're just checking the data against the server. So you could also add the length rule, character rules, whatever on the client side so that it's all "in one place." If you check all that stuff server side, you're working against the ease of jQuery Validate.
1

submitHandler won't fire until the form is submitted for the first time. If you want to check username uniqueness while the user is filling out the form for the first time, you'd need a separate function. The example below assumes you have a page that runs a SQL query to see if the provided username exists in the database, then returns a json string like "{taken:false}" if the username is unique

$('#yourForm [name="username"]').on('blur',function(){
    var username = $(this).val();
    $.get('check/username.php',{username:username},function(data) {
        if(data.taken) {
            // highlight the field and indicate that the username is already taken
        }
    },'json');
}

The specifics of the call to $.get would depend on how your backend is set up. But in general, the process would go:

  • user enters a username
  • user blurs out of field
  • $.get or $.ajax call is made to the server to check uniqueness of username
  • if the response from the server indicates that the username is not unique, handle your validation (higlight the field, add an X icon, etc) and either
    • prevent form submission until the username IS unique, or
    • let the form submit and return an error for duplicate username

UPDATE

If you want to create a new rule for the validation plugin, you can do something like:

function isUsernameUnique(username,field) {
  var unique = false;
  $.ajax({
    url: 'path/to/usernameCheck/',
    data: { username: username },
    async: false,
    success: function(data) { unique = data.unique; }
  });
  return unique;
}

$.validator.addMethod(
    'uniqueUsername',
    isUsernameUnique,
    'That username is already in use. Please choose a unique username.'
);

Then, in your form's validate function:

$('#yourForm').validate({
  ...
  rules: {
    username: { uniqueUsername: true }
    ...
  }
  ...
});

And, a separate blur function for your username field:

$('[name="username"]').on('blur',function(){
  var unique = isUsernameUnique($(this).val(),$(this));
  if(!unique) {
    // handle error
  }
});

This lets you reuse the same function for both your pre-submit validation and your validation plugin. However, I see two issues here:

1 - After your first submit, $.fn.validate() will eagerly validate your username field, meaning the blur event on the username field is no longer required. perhaps you can disable it after the first submit to prevent unnecessary ajax calls

2 - It's not 100% DRY, as you'll need to do your own error handling in the blur event handler

3 Comments

I see, so you're basically just adding a regular call to the server using a manual onBlur function. A few problems with that: how do I notify the Jquery Validation plugin form validation function of the validity of that field? It needs to somehow know whether it's ok to submit the entire form or not. Also, when that username field is invalid in terms of the Jquery Validation plugin validation (lets say it's too short) then for some reason the onBlur function keeps getting called repeatedly.
The custom onBlur seems to work fine except the Jquery Validation plugin has no idea about it. So even if the ajax call returns the the field is invalid, the form is still submitted (jquery doesn't know that the field is invalid). Any idea how I can tell the jquery validation that this field is invalid?
@Guy I realized this morning that I had already solved a similar issue in an old PHP app of mine; I've modified the code somewhat to fit your question and updated my answer. Note the two caveats I mention at the bottom.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.