I’m attempting to make a function that checks the validity of an input field, but I’m running into the problem that if I type too quickly and then hit tab, it doesn’t fire the event and the field isn’t validated. I’ve tried a few combinations of keyup, keydown, blur, focus, and focusout, but nothing has worked.
I have used blur previously, but the problem with blur is that on the last input for their email address, it won’t fire because they shouldn’t tab away from email and blur the box.
This is the code that I’m using currently. It works when I wait, but if I type in “John” and then hit tab immediately, it doesn’t validate it.
$(function()
{
var timer;
// First name
$('input[name="firstName"]').on('keydown',function(event)
{
clearTimeout(timer);
timer = setTimeout(function()
{
validate(/^[A-Za-z]*$/, 'firstName', 'firstName')
}, 800);
});
// Last name
$('input[name="lastName"]').on('keydown',function(event){
clearTimeout(timer);
timer = setTimeout(function()
{
validate(/^[A-Za-z]*$/, 'lastName', 'lastName')]
}, 800);
});
// Email
$('input[name="email"]').on('keydown',function(event){
clearTimeout(timer);
timer = setTimeout(function()
{
validate(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, 'email', 'email')
}, 800);
});
}
Any ideas on what I should do?
Run the function right away on blur. One way is to use 0 with setTimeout, better way to break it out to a function call and call the function.