jQuery validator and a custom rule that uses AJAX

thatweblook picture thatweblook · Apr 13, 2010 · Viewed 80.1k times · Source

I read your reply regarding the jQuery validator where you outline a method to check a username against a value in a database.

Ive tried implementing this method but no matter what is returned from the PHP file I always get the message that the username is already taken.

Here is ths custom method...

$.validator.addMethod("uniqueUserName", function(value, element) {
  $.ajax({
      type: "POST",
       url: "php/get_save_status.php",
      data: "checkUsername="+value,
      dataType:"html",
   success: function(msg)
   {
      // if the user exists, it returns a string "true"
      if(msg == "true")
         return false;  // already exists
      return true;      // username is free to use
   }
 })}, "Username is Already Taken");

And here is the validate code...

username: {
    required: true,
    uniqueUserName: true
},

Is there a specific way i am supposed to return the message from php.

Thanks

A

Answer

Tim picture Tim · Nov 2, 2012

For anyone else who stumbles upon this, validate supports 'remote' method, which may not have existed in 2010:

https://jqueryvalidation.org/remote-method/

$("#myform").validate({
  rules: {
    email: {
      required: true,
      email: true,
      remote: {
        url: "check-email.php",
        type: "post",
        data: {
          username: function() {
            return $("#username").val();
          }
        }
      }
    }
  }
});