Introducing Key Concepts for Form Validation with the DOM - Using the DOM for validating online forms
(Page 3 of 5 )
My initial approach for creating a DOM-based form validation script relies upon defining three core JavaScript functions. The first one will be responsible for checking whether the data entered in the respective form is valid or not, while the second and third ones will be tasked with displaying and hiding error messages respectively via the DOM.
Having explained the driving logic of the pertinent form validation script, I'll define the signature of the first JavaScript function, called "showError()," which logically displays error notifications when a particular form entry is considered invalid. Here's the source code for the mentioned function:
// display error messages via the DOM
function showError(obj,message){
if(!obj.errorNode){
obj.onchange=hideError;
var span=document.createElement('span');
span.appendChild(document.createTextNode(message));
obj.parentNode.appendChild(span);
obj.errorNode=span;
}
valid=false;
return
}
If you examine the above function, then possibly you'll realize that it presents some interesting aspects that deserve an in-depth look. First, this function takes up the input box where the error was originally raised along with the respective error message as the unique incoming arguments.
Obviously, this has a justification. Since the function appends a new <span> node to the offending form field and inserts the corresponding error notice as a text node, it displays errors without having to use alert methods. Wasn't that good?
Also, you can see that an "onchange" event handler is attached to the input box in question, which triggers a new function named "hideError." Again, this makes sense, since the script assumes that the user has changed the wrong value entered in that field, thus the respective error message must be removed from the web document. Now, are you realizing how the DOM is used here for displaying and hiding notification messages? I bet you are.
Well, having explained in detail how the "showError()" function does its business, it's time to move forward and take a look at another relevant function. I'm talking about the "hideError()" function, which will be defined in the following section. Not surprisingly it is tasked with removing the displayed error messages from the web page.
Assuming that you're interested in learning how this new function will be created, click on the link shown below and keep reading.
Next: Removing error messages from the web page >>
More JavaScript Articles
More By Alejandro Gervasio