views:

45

answers:

4

Hi All,

I am making a small form for a php app and had a question regarding javascript validation.

What is the best event to run the javascript validation on the input value? Is it the "focusout" event?

I used "focusout" to originally but it creates problems when the user hits enter while they are still focused on any particular field in the form.

Should I run the js validation when the user clicks submit?

Just looking for some advice.

Thanks!

Chuck

+1  A: 

Should I run the js validation when the user clicks submit?

If you override the actual submit event of the form, you will catch both the submit button and when the user presses the return key.

$('#yourForm').submit(function () {
  // validation ...
  if (valid) {
    return true;
  }
  return false;
});
Matt
A: 

This is an interesting design question, and more than just a technical one. If you check each field when the user leaves it, you would as a consequence be showing the result of your validation somehow, at least if the field value is not "valid". That has to be handled well or it'll be irritating.

Personally I think it's less of a problem to validate upon submit, but for large forms it can be confusing for people to have to go back and re-think something they wish they were done with. Also, as you say, you're sort-of stuck with validating at submit time anyway.

Pointy
A: 

You may want to check out jQuery Validation plugin: http://docs.jquery.com/Plugins/Validation

By default, it will validate on submit, then if there are errors it will validate on the field's onchange event.

Dustin
A: 

I maybe wrong and I often am, but instead of using focusout, you might wanna try using .change()

This should register whatever value that the user entered into the textbox, even if they hit the Return key. In fact, it should register if the user hits the tab key, clicks anywhere outside of the textbox, clicks the submit button, and essentially whenever focus is lost on the form field.

Bug Magnet