Guy
Guy

Reputation: 317

How to specifically validate a certain form field using Jquery Validation plugin

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

Upvotes: 2

Views: 1500

Answers (2)

Evan Davis
Evan Davis

Reputation: 36592

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
});

Upvotes: 2

jackwanders
jackwanders

Reputation: 16020

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

Upvotes: 1

Related Questions