Search code examples
asp.net-mvcvalidationasp.net-mvc-4remote-validation

What is the best way to set up a sort of a timer for user validation using MVC 4


I have set up some remote validation in my controller for email validation so that the email can be verified right away. I am hoping to take this a little bit further and validate the email as the user is still typing. Right now it validates when the user takes the focus off of the text box for the first time but if they go back to the text box, it will validate on a key up. Is there a way to set up remote validation with a different trigger? Maybe even a key up but after a certain amount of time has elapsed?


Solution

  • You can do this with a basic setTimeout in Javascript before running your validation code.

    A quick example using jQuery:

    $('#myElement').keyup(function(){
         setTimeout(ValidationFunction,1000);
    });
    

    If you need to clear the timeout when a key is pressed you can do:

    var myTimeoutFunction;
    
    $('#myElement').keyup(function(){
             myTimeoutFunction = setTimeout(ValidationFunction,1000);
        });
    
    $('#myElement').keydown(function(){
         window.clearTimeout(myTimeoutFunction);
    });
    

    Here's a working example