Apply validation functions in the form of a waterfall

1

I'm developing a system and want to do validations through functions.

I have the checkUsername function that does query in the database to return me whether or not it can register with that username.

And then you have other functions to check other things like checkEmail . How to apply these functions one after another in a form submit?

Examples of functions I'm using:

function checkUsername(username){
    $("#username").focusout(function() {        
        var username    = $("#username").val();
        var pattern     = /^[a-z0-9_-]{3,16}$/;
    if (pattern.test(username)) {
         var Urlverificadora = 'action=verificar_username&username='+username;
         $.ajax({
            type : 'POST',
            data : Urlverificadora,
            url  : painel+'checkUser.php',
            success: function(responseText){ // Get the result and asign to each cases
                if(responseText == 0){  
                    $("#username").css("border", "2px dashed green");
                } else if(responseText > 0){
                    $("#username").css("border", "2px dashed red");
                } else{
                    alert('Entre em contato com o administrador.');
                } //success
            }
        }); //ajax
    } else {
        $("#username").css("border", "2px dashed red");
    };}
)};
    
asked by anonymous 23.07.2014 / 13:49

3 answers

1

I see two options:

Do the syncrona validation

You can use the async: false option in jQuery to force the code to "wait" for the validation response of each of its functions. Although I present this option first I do not recommend it because if the ajax call takes your code it is "hung" and you do not even notice it.

Example:

$.ajax({ url: "ficheiro.php", 
        data: {data: dados}, 
        async: false,
        // etc

Do submit delayed via javascript

You can stop the submission of form like this:

$('form').on('submit', function (e) {
    e.preventDefault();
    // talve seja bom criar aqui um overlay que indica que está a ser processado

and at this point the code runs its functions for validation. Since it has several and the answers will arrive at different times you can save a variable with all the answers. An array of booleans, or an increment variable, or another. Then you can have a setInverval that will check if the answers have arrived. Or, you can chain these validation functions to trigger one after the other, from within the success function.

Anyway, when the conditions are met, and to resume the submit , you can do so:

$('form').off('submit').submit();

This removes the shadow from submit of the form, and then makes the submit defenitive.

In case the submit (after accepted validation) is also submitted via AJAX, then you just need to make a new ajax call with form data instead of the last line I wrote above.

    
23.07.2014 / 19:56
2

I believe your validation should be done, of course, on both the front end and the backend, so you can work on changing the focus of the field.

$("#username").blur(function(){
    if(checkUsername($(this).val()){
        $("#username").attr("class","invalido");
    }
}):

and can also work with the submit form.

$("form").submit(function(){
    $("input").each(function(){
        if($(this).is("#username")){
            if(checkUsername($(this).val()){
                $("#username").attr("class","invalido");
                return false;
            }
            if(checkEmail($(this).val()){
                $("#email").attr("class","invalido");
                return false;
            }
            if(checkPassword($(this).val()){
                $("#password").attr("class","invalido");
                return false;
            }
        }
    });
}):
    
23.07.2014 / 15:21
1

You can control the call of your functions in the .submit() function of jQuery:

$( '#send_form' ).submit(function(){ 
   //aqui você poderia adicionar suas funções validadoras. 
   if( name == false ){
      return false; // Caso a var name esteja como false ele não envia o form.
   }
});

And in the case of your AJAX I recommend that you control through .change() :

$( '#username' ).change(function(){
   //chamada ajax e controlador da chamada como adicionar borda ou etc..
});
    
23.07.2014 / 14:55