April 19, 2006

JavaScript Form Validation methods

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 9:35 am

As there is always a need for client side validation with Website design I thought I would discuss a few different implementation methods that may help with the process. JavaScript is always a popular choice for this, and contains generally all validation that we need for simple forms. These days JavaScript validation logic has been extended by allowing the server to help with some realtime validation using AJAX which allows us to do more complex checks, like checking the username exists on the server before submitting etc. For the moment this article will discuss the implementation of form validation methods, and I will provide some examples in the future.
As a note, we must always assume that JavaScript can be disabled on a clients browser. This typically has occured since people have been afraid of JavaScript exploits for MS IE, popup windows and the such. Hopefully since WinXPSP2 (I am yet to check) is whether people are feeling more confident leaving JavaScript on. So, because of this, we must always allow our form to operate without requiring the use of a custom JavaScript submit function. More importantly we should always remember that client side validation does not substitute server side validation and it must always be performed. Client side validation will make your forms feel more reponsive to the user as simple errors can a majority of the time be ruled out with simple JavaScript checks.

For us to make use of form validation correctly, we must first code up our form with a submit button. We then can use various event listenner/triggers that occur during our client entering form values to call JavaScript validation methods. Most popular events that we can use is the onsubmit(); and onchange();. You can read more about intrinsic events on W3C here to see what additional events occur for HTML elements.

Onsubmit

This method is used as a sort of hook allowing us to call validation or logic checks prior to the form being submited to its action. It allows you to call a function which can return either a true or false state, allowing you to specify whether to submit the form or not.

If you are using Macromedia Dreamweaver and are looking for some basic quick validation (mandatory fields, email address/number validation, minimum length and the such) you can use their Validate Form behaviour (by selecting ‘window -> behaviours’ then selecting your form [has to be selected to work correctly] and selecting add behaviour -> validate form on the behaviours window). For our explanation, it places a generic ‘all in one’ JavaScript validation method in your header that allows it to accept many parameters and rules. The function is called using the onsubmit function tied onto the form element. The function processes, displaying an error message and then sets a document variable which returns true or false. This is great for very quick validation, but lacks largely in the logic you can perform, you can’t do a particular check based on a selection of the form elements.

From here you may choose to extend the form validation and write your own method, allowing you to compose your own onsubmit function and implement your own extended logic/error messages. Your function either needs to return true/false (which in turn is returned from the onsubmit call, e.g. onsubmit=”javascript:return myOnsubmit();”). This opens up many different ways of handling form validation, but also now means that we potentially have to start considering non-reusability etc.

To help validate your form, you should try and collect a number of validation methods for particular purposes, such as checking for required fields, checking email address syntax and the like. These can be placed into a single JavaScript script and included onto each form page. You can then make your custom logic checks for the form in a concise form.

Another more advanced way of handling this step is to create your own Validation Class and then generically register validation checks on field elements. For sake of extending the flexibility of your design, you could also allow the register of validation functions that return true/false to extend its capabilities. This would then also contain all standard logic (such as required field checking methods, validation of email addresses etc). Through many declaritive statements you could setup a quick way of performing basic field validation and allowing it to be extended with an additional logic method.

How to handle the error messages becomes an issue, and is one of the great downfalls of the Dreamweaver implementation. How you place in your error message is upto younow that you have written your own class, but here are some different implementation methods; inline javascript, through your declaritive call (assigning to a variable) or using a hidden form field (with a naming convention - that could be checked by your validation method to see if it exists, and if so grab the message from its value). All have pros and cons, most likely the best choice would be variables through your declartive statements.

Onchange

On change event is another event that allows us to register a method that is called if the form value has changed since gaining focus, and is triggered after the element loses focus. We can use this method to immediately provide feedback about the users input as they are filling out the form, prior to hitting the submit button.

Using this method we can do several things, from alerting error messages to changing the elements CSS style from one colour representing valid to invalid etc.

As explained under the onsubmit action, we can use our validation class methods to help validate these fields generically.

March 30, 2006

Base HREF and Javascript Location.href with IE vs NN

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 4:16 pm

Just having a play with some JavaScript to generate a URL to redirect the user to.It appears that IE does take into consideration your < base xhref="" mce_href="" > in your header when executing a location.href=”" mce_href=”" command with IE. It does however work with NN. In my scenario it was due to a having images and CSS work relative to a different folder, with operations occuring in a different folder. This was due to my templating setup.

Instead of simply calling:

location.href=”myotherfolder/?do=whichever”;

you can build the whole URL using

location.href = window.location.protocol + “//” + window.location.host + window.location.pathname + “myotherfolder/?do=whichever”;

which sidesteps your base href declaration in your head HTML. May be useful to keep in mind.

March 15, 2006

Simple Email Validation with Regular Expressions

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 3:30 pm

Email validation in PHP can be done in a few strategies (some too exhaustive)
- Checking the syntax of the email address
- Providing the user two fields to repeat their address
- Providing an email confirmation
- Checking the domain MX records
- Verifying the mail account through communication with the MX

Usually that later few methods take too long to implement and can be open to many problems that we don’t want, such as reliance of the operating system, connectivity to the MX and DNS records (Which may cause people to get frustrated signing up with a legitimate email address). Where possible you should prompt the user for their email address twice to ensure that they have nominated the correct email free from typos that still pass basic syntax, eg. cmaeornmanderson@gmail.com opposed to cameronmanderson@gmail.com.

The syntax can be checked once again in two spots, the client side first (to give them an opportunity to fix) and then on the server side.

< input type="text" name="emailAddress" id="emailAddress" onchange="javascript:validate('emailAddress', emailAddressRegex, 'Please ensure your email address is correct');" />

As suggested in an earlier post, if we use Regular Expressions (perl) to check the format we can use the same syntax in JavaScript (for client side) as we do in PHP/VB/Java etc.

On the server side we can see that this can be compiled as a perl regular expression to match against their form submission:

< ?php

...

$emailAddressRegex = '/^[A-z0-9][\w.-]*@[A-z0-9][\w\-\.]+\.[A-z0-9]{2,6}$/'; // Could be in our standard library somewhere

$emailAddress = $_POST['emailAddress']; // Access the request->getParameter(’emailAddress’);
if(!preg_match($emailAddressRegex , $emailAddress)) {

// Add the error to our action errors

die(’Invalid email address detected’);

}


?>

We need to ensure we check the email address again on the server as it is quite easy for a legacy browser or browser with JavaScript disabled to submit the field (infact our method doesn’t stop the user from submitting for form if they know there is an error).

Your regex could be a lot more specific depending on the situation. When matching against formats it is best to read the RFC or similar. For email a good resource is located on Wikipedia.

March 14, 2006

Simple JavaScript Validation using Regex

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 2:49 pm

Sometimes it is important to validate a users input, such as entering a number, decimal value or an email address. Validation of the input can occur in two locations, the Client and Server realm. The Server realm allows us to validate user input one the user has pressed the submit button. We receive the users input and we can easily validate their input for the correct format. You should always validate a users input on the server side.

To make the process quicker you should also take advantage of the client realm as well. This will allow you to quickly pick up mistakes and allow the user the opportunity to fix the mistakes before submitting the form to the server for validation.

A great way of checking the simple input it to use JavaScript Regular Expressions.

Regular expressions can be both used on the Client and Server side to ensure that an inputted text contains the correct format. This may be checking that the input is only numbers, or is a number with a decimal value etc.

Regular expressions are very easy to implement and are very reusable.

I simple way of invoking a validation check is to use the form elements event handlers (onchange, onblur etc).

< input id="myfield" name="myfield" onchange="javascript:validate('myfield',currencyRegex,'Please ensure the value you have entered is a currency format (x.xx)');" />

My generic validate JavaScript file – validate.js contains:

< !—
// REGEX
var currencyRegex = /^\d+\.\d{2}$/;
var numberRegex = /^\d+$/;

// Validate Function
function validate(fieldId, regex, message) {
field = MM_findObj(fieldId).value; // You can use document.getElementById(fieldId).value; but I prefer using Macromedia’s MM_findObj javascript function
if(!field.match(regex)) {
alert(message);
}
MM_findObj(fieldId).focus();
}
–>

You can then find and collect various regex expressions commiting them to your standard validate.js file, and use them often to help ensure feedback of simple string matching/formats is quick and does not require the user to hit submit for server side response.

Various JavaScript REGEX’s can be found through google very easily, and the syntax is very easy to learn, and very powerful.

« Previous Page