ptg16476052
Validating Forms with JavaScript 535
19
There was no need to change the source code for the page at all other than to add the
JavaScript tags to load the jQuery library and the custom script for the page, as men-
tioned previously.
Then there’s the custom script itself. Here are the full contents:
$(function() {
$("#registrationForm").submit(function (event) {
if (!$(this.name).val()) {
event.preventDefault();
alert("You must enter a name.");
}
if (!$(this).find("input[name='gender']:checked").length) {
event.preventDefault();
alert("You must select your gender.");
}
console.log($(this.name).val());
});
});
Improving Form Validation The form validation code in this exercise works, but it
could be better. The biggest problem is that it shows an alert for each field with an error.
A better approach is to show an error on the page and highlight the fields that need to be
corrected before the page can be submitted. The validation code is the same; what’s dif-
ferent is what happens when errors are found.
In this case, I’m going to print an error message above the form, and I’m going to mark
each field with invalid input to indicate that it needs to be corrected. Before I get to the
JavaScript, I’m going to add a few styles to the style sheet that will be used for the vali-
dation messages. Here are the new styles:
div.error label {
color: red;
}
div.errors {
border: 2px solid red;
color: red;
width: 50%;
padding: 10px;
}
The first style is applied to labels inside div elements with the error class. The second
style is applied to a div with the class errors. This should provide some insight into how
the validation code will work. When a field is found to have invalid input, an error mes-
sage will be saved so that it can be placed in the errors div, and the class error will be
applied to the div containing that field.
▼
▼