Search code examples
javascriptjqueryonchangeonkeyup

which is the best way to validate an input with jQuery? onChange / onKeyUp. Or what other?


someone could explain which of the two is the best and why? or if there is a better option.

also is there other options like keydown, blur, change...

"why" is very importan. thanks a lot.


Solution

  • onKeyUp would result in the validation routines running after every key press. This could be viable if using a setTimeout as mentioned by @APAD1, but depending on the time, the user could leave the field before the validation routine, and depending on the form have submitted before the validation routine. This can also be very heavy. I would generally only use onKeyUp if you can validate the individual key press and swallow it. If you are waiting for final input to validate, then use onChange or onBlur.

    onChange works for any field that would be picked up by the $(":input") selector (e.g. radios, selects, SLEs, etc). This is useful if you want to validate when they leave, but will only work if you re-focus the field and clear the bad contents. Else they could just ignore the error and keep going. If they never re-change the contents, the validation won't fire.

    onBlur is very good if you want to validate as soon as input is complete and the field loses focus. I caution using this, depending on how you are notifying the user of the error. If you are alerting or doing something like re-focusing the field, then you can create a bad, blocking user experience.

    As a general thought process, it is good to do instant validation on inputs, but inform the user in a non-blocking way (e.g. pop a div next to the field or something). ALWAYS preform a final validation of the entire form before sending information, as in some cases it could be possible for the user to ignore the validation messages, and subsequently send bad information.