Exception Handling in JavaScript: Validating forms Introduction - Setting the basics of form validation: defining custom error objects
(Page 2 of 4 )
Before I start by defining the JavaScript functions that comprise the form validating program, I’d like to explain its logic, so when you see the source code, it will be much simpler to read and understand.
Validating forms through exceptions is a pretty straightforward process, which closely resembles traditional client-side checking methods. For this particular case, I’ll set up a regular contact form comprised of some of the usual fields such as First Name, Last Name, Email and Comments. Then, I’ll define a function to check whether the fields have been filled in. In case it finds an offending field, the script will display an error message by using some DOM methods to modify the document’s structure. As you can see, the whole checking process is extremely understandable.
So far, as described before, the logic for validating forms is nearly identical to that utilized with the usual techniques. However, the main difference rests on how errors are handled when a specific field hasn’t been filled in. Since JavaScript allows us to create custom error objects, each time the scripts find an offending field, an error object will be thrown within a “try” block and then trapped by the appropriate “catch” block.
Once the error has been caught, the only thing to be done in order to get the validating script working is to define the proper error handlers. Of course, this process will be understood best if you’re able to study the code, thus I’ll begin defining the core “validateForm()” function, which looks like this:
function validateForm(){
valid=true;
try{
var fields=document.getElementsByTagName('form')[0].elements;
if(!fields){return false};
// validate First Name field
if(!fields['fname'].value){
throw new Error('fname|Enter your First Name');
}
// validate Last Name field
if(!fields['lname'].value){
throw new Error('lname|Enter your Last Name');
}
// validate Email field
if(!fields['email'].value){
throw new Error('email|Enter a valid email');
}
}
// catch all errors
catch(e){
genericErrorHandler(e);
}
return valid;
}
As you can see, the above function checks to see whether the required fields have been filled in. In case the function finds an empty field, a custom error object is created and the proper warning message, together with the name of the offending field, are passed concatenated as one single argument for the error object constructor. This concept is clearly illustrated with the following lines:
if(!fields['fname'].value){
throw new Error('fname|Enter your First Name');
}
// validate Last Name field
if(!fields['lname'].value){
throw new Error('lname|Enter your Last Name');
}
// validate Email field
if(!fields['email'].value){
throw new Error('email|Enter a valid email');
}
Since all the custom error objects are created within the corresponding “try” block, they will be trapped by the “catch” statement and program flow will be moved to the “genericErrorHandler()” function, as listed below:
catch(e){
genericErrorHandler(e);
}
Additionally, the “valid” variable acts like a simple Boolean flag to indicate whether the form has been completed or not.
Before I move on to writing the next functions, a brief explanation is in order here. Notice that no specific validation is performed on the email field. Probably, you might want to use a regular expression to make sure that at least a well-formed email address has been entered, similar to the following expression:
if(!/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z])+$/.test
(fields['email'].value)){
throw new Error('email|Enter a valid email');
}
However, the reason for applying only basic validation is to overcome a bug of Internet Explorer, which is particularly slow in parsing regular expressions, causing error objects to be created and thrown before the regular expression engine finishes processing a given pattern. On the other hand, Firefox will process the error flawlessly.
Now that you’re aware of this problem, I can move on to defining the corresponding functions for handling and displaying errors. Thus, join me in the next section to see how error handling is programmed.
Next: Manipulating errors: defining custom error handling functions >>
More JavaScript Articles
More By Alejandro Gervasio