Enable jQuery Validate (plugin) with the ajax response

Asked

Viewed 411 times

0

I always found interesting this plugin, as it leaves the form simple with subtle messages to the visitor. I decided to implement and falls into the following dilemma:

How do I get back my AJAX to activate some warning in my form? for example:

I have a simple input with the user name, with min-lenght of 2. If I put 1 character only, it will activate and warn that it needs to have 2, but and in case I need to make an ajax request to my server and check if this name already exists in my database?

If it exists, it proceeds normal, if not, shows the error (same as with min-lenght)

my current code:

$(document).ready(function(){    

var validator = $("#contactform").validate({
    rules: {
        name: {
            required: true,
            minlength: 2
        }
    },
    messages: {
        name: {
            required: "Preencha o nome",
            minlength: "Minimo: 2 caracter"
        }
    }
    submitHandler: function(form) {
       $("#contactform").submit(function(e){
            e.preventDefault();
           $.ajax({
                type: "POST",
                url: "form.php",
                data: $(this).serialize(),
                success: function() {
                    if (result.status == "OK") {
                        // aqui está tudo certo e aparece um aviso
                    }else{
                        // ESSA É A DÚVIDA: caso o nome exista, ele ativa o input com a mensagem de retorno
                    }
                }
            });
            return false;
         });
    },
});
});
  • take a look at my answer below.

1 answer

1


The jQuery Validate plugin has a feature called remote method, where it executes a request to check the validity of the element.

In your case, it would look more or less like this to perform server-side validation:

$(document).ready(function(){    

var validator = $("#contactform").validate({
    rules: {
        name: {
            required: true,
            minlength: 2,
            remote: {
               url: 'validate.php'.
               type: 'post',
               data: { name: $('#name').val() }
            }
        }
    },
    messages: {
        name: {
            required: "Preencha o nome",
            minlength: "Minimo: 2 caracter"
        }
    }
    submitHandler: function(form) {
       // removido para ter brevidade
    },
});
});

Since your method can return a message in string form that will be displayed as validation message for the field.

More information can be found on the link https://jqueryvalidation.org/remote-method/

  • That’s just what I needed, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.