0

I am using JavaScript to validate some form fields. My question is about the code inside

$("#alias").keyup(function(){

This is my script for the validation:

<script type="text/javascript">

$(document).ready(function(){
console.log("principio");


// Setup the ajax indicator



    // Ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function(){ 
  $('#ajaxBusy').show(); 
}).ajaxStop(function(){ 
  $('#ajaxBusy').hide();
});

//control de alias
    $("#alias").keyup(function(){


        var ID=$("#alias").val();
        var REST=$("#rest").val();
        var ACTUAL = "<?php echo $row_Recordset1['alias_mesero']?>";

        $.post("check_username_edit.php", { username: ID, rest: REST, actual: ACTUAL},

                function(result){
                    console.log(result);
                    //if the result is 1
                    if(result == 1){

                        document.getElementById('mensajealias').innerHTML ="Nombre corto disponible";
                          document.getElementById('boton').style.visibility='visible'; // hide 
                             document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";

                    }
                    else if(result == 2){

                        document.getElementById('mensajealias').innerHTML ="No ha modificado el nombre corto";
                          document.getElementById('boton').style.visibility='visible'; // hide 
                             document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";

                    }
                    else if(result == 0){

                          document.getElementById('mensajealias').innerHTML ="Nombre corto no disponible, ya existe";
                           document.getElementById('boton').style.visibility='hidden'; // hide 
                             document.getElementById('mensajeboton').innerHTML ="No se puede insertar hasta que no modifique los datos";

                    }
            });



    });

//control de rest
    $("#rest").change(function(){


        var ID=$("#alias").val();
        var REST=$("#rest").val();
        var ACTUAL = "<?php echo $row_Recordset1['alias_mesero']?>";

        $.post("check_username_edit.php", { username: ID, rest: REST, actual: ACTUAL},

                function(result){
                    console.log(result);
                    //if the result is 1
                    if(result == 1){

                        document.getElementById('mensajealias').innerHTML ="Nombre corto disponible";
                          document.getElementById('boton').style.visibility='visible'; // hide 
                             document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";

                    }
                    else if(result == 2){

                        document.getElementById('mensajealias').innerHTML ="No ha modificado el nombre corto";
                          document.getElementById('boton').style.visibility='visible'; // hide 
                             document.getElementById('mensajeboton').innerHTML ="Ahora puede insertar los datos";

                    }
                    else if(result == 0){

                          document.getElementById('mensajealias').innerHTML ="Nombre corto no disponible, ya existe";
                           document.getElementById('boton').style.visibility='hidden'; // hide 
                             document.getElementById('mensajeboton').innerHTML ="No se puede insertar hasta que no modifique los datos";

                    }
            });



    });



});

</script>

If the user enters the text character by character, the validation takes place like a charm. But I have detected that if the user enters the text very quickly, then sometimes the validation doesn't return the right value.

I guess I could use change(function) instead of keyup(function), but I would prefer that the user doesn't have to leave the field to be validated.

Any advice is welcome.

  • 1
    Can this be helpful : http://stackoverflow.com/questions/4220126/run-javascript-function-when-user-finishes-typing-instead-of-on-key-up – Farax Jun 19 '14 at 23:48
  • 1
    You can validate on every key, but you should always still validate before you submit in case there was some rapid entry and you didn't get a validation done before the submit. Also, you ALWAYS have to validate on the server because client validation is really just UI sugar to help advise the user about what the did wrong, but can always be bypassed. – jfriend00 Jun 20 '14 at 00:02

2 Answers2

0

I have used this approach on a search box that I only wanted to execute the search when the user stopped typing for a short period of time:

var delay = (function () {
    var timer = 0;
    return function (callback, ms) {
        clearTimeout(timer);
        timer = setTimeout(callback, ms);
    };
})();

$("#alias").on('propertychange keyup input paste', function () {
    delay(function () {
        //validate
    }, 1000);
});

It starts a timer for 1 second when any of those events fire and only executes the validation if the timer expires. If any new events are received the timer is reset to 1 second. This event handler also works for cutting and pasting from/to the input.

ajaybee
  • 146
  • 5
-1

Two points for you to consider: 1) Old style Keyup keydown events are not reliable. You always need backup validation from the backend if you use them. If the user inputs quickly, few keyup events will be fired but you are not even sure which event first. 2)Morden Browsers support new events like "input", if possible you should use new events.

John Jin
  • 79
  • 4
  • You need "backend" (server) validation regardless of any "frontend" (browser) validation. Period. – Jared Farrish Jun 20 '14 at 00:23
  • You are absolutely right. His validation is on the backend already. Instead we might call it: backup validation? – John Jin Jun 20 '14 at 00:27
  • The validation is on the backend already? This is Javascript; it runs in a browser? – Jared Farrish Jun 20 '14 at 00:28
  • If you read the code, he called backend function to validate every time, I feel. But that is not good anyway. – John Jin Jun 20 '14 at 00:29
  • OK up to you to say what ever you like. Hope I haven't misunderstood $.post is calling the server. – John Jin Jun 20 '14 at 00:40
  • Alright, I missed those. However, calling the server in an ajax to do client-side validation does not obviate the need to do validation *on the server when submitting the actual form*. Consider: Server's busy on the username check requests, somebody submits the form anyways (or disables Javascript, or submits it manually...) and that username could now be in the `users` table twice, because the *server* didn't validate the username before creating a new entry. – Jared Farrish Jun 20 '14 at 00:46