Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

Validating Forms with JavaScript 537

19


}


if (errors.length > 0) {
$(this).prepend("

You must "



  • "correct the following errors:
      "
    • errors.join("") + "
");
}
});
});

If you include this code in your page and test it, you’ll see that when you submit an
invalid form, it properly marks the labels of invalid fields, prints the error message at
the top form, and prevents the form from being submitted. However, one bug should be
fixed. What happens when you submit the form with invalid input a second time? As
you’ll see, a second set of error messages will be printed at the top of the page. To fix
this bug, I just need to add the following line to the event handler:


$("div.errors", this).remove();


I added it right before the if statement that checks whether to print the error messages. It
uses the jQuery remove() method to remove any elements that match the selector.


The final form with all of the error messages for invalid input displayed appears in Figure
19.5.


FIGURE 19.5
An alert message
for multiple fields.



Free download pdf