Apply cascade validation functions

Asked

Viewed 237 times

1

I’m developing a system and want to make validations through functions.

I have the function checkUsername who consults at the bank to return to me whether or not to register with that username.

And then you have other functions to check other things like checkEmail. How to apply these functions one after the other in 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");
    };}
)};
  • Interesting your question, you can control Submit how to disable until all validations are correct. In the specific case of the user, it would be good if you listened to the changes through an event. So, the user would already know if he has the right username before submitting the form.

  • #Ronny Amanrante (@Ronny Amanrante), could you demonstrate this in code so I know how to structure the validations and how to call the script through Submit? Since there are functions, I do not know how to apply them in cascade form!

3 answers

2

I believe that your validation should be done, of course, both in the front end and in the back end, 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 form Ubmit.

$("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;
            }
        }
    });
}):
  • For this to work, you will need to change AJAX to synchronous (async: false) and modify a variable inside the Success Calback to return the boleano value.

1

You can control the calling of your functions in the function .submit() 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 recommend that you control through the .change():

$( '#username' ).change(function(){
   //chamada ajax e controlador da chamada como adicionar borda ou etc..
});
  • 1

    If you want me to be more specific on something, give a touch here in the comments.

  • #Ronny Amarante, can you please give me an example of 2 validations, for example, username and email together? Would it be an "if Else" for each check and if at the end there was at least a "Return false" the form would not be submitted? And as "separate" or "together" validation with function?

  • if( name == false ){
 return false; // Caso a var name esteja como false ele não envia o form.
 } else if( email == false ){...}...

  • If Submit receives a false return it will not send. And depending on the amount you could even use: (x < 10 && y > 1). Depending on the size of the validations and their amount, I would use the Revealing Module Pattern

1


I see two options:

Do the synchronous validation

You can use the option async: false jQuery to force code to "wait" for the validation response of each of its functions. Although present this option first do not recommend because if the call ajax take your code is "hung" and the user does not even notice what is happening.

Example:

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

Make Ubmit delayed via javascript

You can stop the submission of form thus:

$('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 other. Then you can have a setInverval that checks if the answers have already arrived. Or, you can chain these validation functions to fire one after the other, from within the Success function.

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

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

This removes the headphone from submitof the form, and then makes the defective Submit.

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

Browser other questions tagged

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