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

(singke) #1
ptg16476052

Validating Forms with JavaScript 531

19




I’ll be using jQuery to write the form validation code. So, I’ll add the following code to
the page right above the closing tag:



This loads jQuery from a CDN so that your page will load faster.


Then load the form.js script. I placed mine in the scripts subdirectory, like this:



In this script I use jQuery’s document.ready handler to bind an anonymous function to
the submit event of the form, which has the ID registrationForm:


$(function() {
$("#registrationForm").submit(function (event) {
alert("Form submitted");
event.preventDefault();
});
});


The Validation Function When you write an event-handling function for jQuery,
you can specify that the function accepts an argument, which represents the event that the
handler is handling. In this case, I named the argument event for simplicity. In the han-
dler, I display an alert, just to demonstrate that the JavaScript is working, and I call the
event.preventDefault() method. This is a special method provided by jQuery that indi-
cates that the default behavior associated with the event should not occur. In the case of a
form submission, it prevents the form from being submitted. When the form validation is
complete, the default action will only be prevented when the form input is not valid.


Testing For Required Fields The form has three required fields: Name, Gender,
and Operating System. The validation function is responsible for checking that they each
contain a value. The name field is a text input field. Here’s the markup for the field:



Before writing the test to verify that the form field is not empty, the trick is accessing the
value in the field. I’ve updated my event handler to look like this:


$("#registrationForm").submit(function (event) {
event.preventDefaul t();
console.log($(this.name).val());
});



Free download pdf