Enable jQuery Validate (plugin) with ajax response

0

I've always found this plugin interesting because it leaves the form simple with subtle messages to the visitor. I decided to implement and fall into the following dilemma:

How do I make the return of my AJAX activate some warning on 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 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, it shows the error (same as 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;
         });
    },
});
});
    
asked by anonymous 07.08.2018 / 20:26

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 something 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 the form of a string that will be displayed as a validation message for the field.

More information can be found at link

    
07.08.2018 / 22:07