10.07.2017 Views

246996016-HTML5-Step-by-Step

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

300 Chapter 16<br />

Validating a Web Form with jQuery and JavaScript<br />

One typical use of JavaScript is to validate a Web form, or more appropriately, prevalidate<br />

a Web form. When a Web form is submitted, it is sent to a server-based program<br />

which can then do something useful with the data, such as complete an order, or store<br />

the data in a database. However, using JavaScript for validation provides no security for<br />

the server-based program.<br />

Don’t Substitute JavaScript Validation for Server-Side Validation<br />

There is no guarantee that the visitor to your Web page has JavaScript enabled in<br />

their browser. Therefore, you cannot rely on JavaScript as the sole means to verify<br />

that the user has entered properly formatted data. More than one Web site has<br />

been hacked because the programmer relied solely on JavaScript to validate and<br />

verify the contents of user input from a Web form.<br />

All data must be verified at the server or within the server code. No amount of<br />

JavaScript validation, trying to require JavaScript, or other tricks will ensure that the<br />

data is safe. Always verify data at the server. When used as a means to validate form<br />

data, JavaScript is to be used only to enhance the user experience <strong>by</strong> providing<br />

early feedback on known invalid data. JavaScript is never—and should never be—<br />

used to truly test whether the data is valid.<br />

With that in mind, here’s a simple form and some JavaScript/jQuery code to validate the<br />

text box on the form:<br />

<br />

<br />

<br />

<br />

jQuery 101<br />

<br />

<br />

<br />

<br />

Answer: <br />

<br />

<br />

<br />

$("#myForm").submit(function() {<br />

if ($("#firstName").val() == "Yes") {<br />

alert("Form entered correctly");<br />

} else {<br />

alert("Form not correct");<br />

return false;<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!