14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

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

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

Chapter 9 ■ Data ValiDation teChniques<br />

form.addEventListener("submit", function(event){<br />

if(email1.validity.valid && email2.validity.valid && email1.value && email2.value){<br />

resultDiv.innerHTML = "Email is valid <strong>and</strong> they match";<br />

}else{<br />

resultDiv.innerHTML = "Email is not valid or they do not match";<br />

}<br />

event.preventDefault();<br />

}, false);<br />

}<br />

document.addEventListener("DomContentLoaded", addInteractedClass, false);<br />

<br />

Showing a List of Erroneous Fields<br />

This method shows the user a list of fields that contain errors. (See Figure 9-4.) In addition to adding a border to<br />

visualize if the field is valid, you will loop through the form fields to generate a list of all the invalid fields.<br />

Figure 9-4. Showing a list of erroneous fields<br />

Once the page loads, you add an event listener to the form. When the form is about to submit the data, you stop<br />

the form <strong>and</strong> call the checkInputs function.<br />

The checkInputs function first looks at a div called resultsDiv, where you give the user feedback <strong>and</strong> empty out<br />

any nodes that are in that div. Then it loops though all the input tags <strong>and</strong> checks for the valid property of each tag.<br />

If the tag is not valid, it then grabs the ID, asks for the properly-formatted name through the reformatName<br />

function, <strong>and</strong> continues to create a paragraph node <strong>with</strong> text indicating the name of the field is invalid <strong>and</strong> adds this<br />

new node to the resultsDiv.<br />

showInvalidFields.html (excerpts)<br />

<br />

function formCheck(){<br />

var form = document.getElementById("userForm");<br />

form.addEventListener("submit", function(event){<br />

www.it-ebooks.info<br />

291

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

Saved successfully!

Ooh no, something went wrong!