gom
gom

Reputation: 897

real time validation of username using javascript and ajax

I've written a script for my registration form that if there's a keyup event on the username input field, then javascript checks if the username entered is valid and if it's then an ajax function is called to check its availability.

It's working fine. But username can be entered without doing a key up, what to do for those cases? E.g. username can be entered by clicking the input field and selecting a name suggested by the browser, Or by using an auto-form filler. There's no "keyup" in these cases, so what to do for these cases?

And if I am missing some case then pls tell.

Upvotes: 0

Views: 1918

Answers (3)

Joyce Babu
Joyce Babu

Reputation: 20654

Bind the callback to the change event too.

Instead of $('username_input').keyup or $('username_input').bind('keyup', callback) use

$('username_input').bind('keyup change blur', function () {
    //
})

[UPDATE]

If you are not using jQuery try

function checkUserName() {
   // Ajax validation code
}
userinput = document.getElementById('yourusernameinputid');
userinput.onclick = userinput.onchange = userinput.onblur = checkUserName;

on a side note, you should try learning jQuery. It could save you a lot of time, and help you make better sites in less time.

[UPDATE 2]

It looks like there is no way to detect change via autofill using events. You need to set a timer to automatically check your input at fixed interval and check with you last value.

(function() {
   // It is always better to use a closure to prevent the value from 
   // getting overwritten by another piece of code
   var value = '';
   setInterval(2000, function() {
      if (userinput.value != value) {
           checkUserName();
           value = userinput.value;
      }
   });
})();

Upvotes: 4

davidbuzatto
davidbuzatto

Reputation: 9424

  • Test the username when:
    • The blur event occurs (when the text field loses its focus), and
    • Before the user sumits the form, or
    • The change event occurs (I think this is the best).

Upvotes: 0

Related Questions