Sunday, September 11, 2011

Advanced jQuery Form validation (1): check a phone number format

The jQuery Validation plugin is a very powerful plugin aimed at form validation.

Among its main features, you can create your own validating methods. In that example, we will check a French phone number against the international format.
French phone numbers are made of ten digits, starting with 0 (zero), grouped by two and usually separated by dots or spaces (e.g.: 01 23 45 67 89). In the international format, the country code for France (33) prefixes the actual phone number, and the first digit is set between parenthesis. For a better readability, we use the space character as separator (e.g.: 33 (0)1 23 45 67 89). 


The form validation is made of three parts: the HTML form, the javascript validator method, and the javascript form validator set of rules. 

In the HTML form, we set the maximum length of the phone field in case javascript is deactivated, thus following the principle of graceful degradation. In that case, all the checkings have to be done on the server side too. If any formatting of the data entered by the user is done on the server side, the best practice is to show the form back to the user, with the formatted data highlighted for her last validation.

<form id="myFormId" method="post">
    <label for="phoneId">Phone number</label>
    <input type="text" name="phone" id="phoneId" maxlength="19" value="" /><br/>
    <input type="submit" value="Submit" />
</form>

The validator only checks if a phone number is either empty (in that case no event is triggered) or if it is written in the international format. If not, we send the error message to display. 
The core of it is a regular expression to check the exact string format we want. 

The form validator set of rules links them to the form id (myFormId) and to the phone input field name (phone). The only rule applied is the one defined by the new validator (myPhoneNumberValidator).

$(document).ready(function(){
    jQuery.validator.addMethod("myPhoneNumberValidator", function(value, element) {
        // no phone number is a good phone number (the field is optional)
        if (value.length == 0) { return true; }
        // if the phone number field is not empty, it has to follow the fixed format
        return /^33 \(0\)\d \d\d \d\d \d\d \d\d$/i.test(value);
    }, 'Please enter your phone number in the following format: <i>33 (0)1 23 45 67 89</i>');

    $("#myFormId").validate({
        rules: {
            phone: "myPhoneNumberValidator"
        }
    });
});

We can go a bit further by rewriting a phone number entered with no separator into the international format directly during the check. If the phone number is not empty, is not already in the targetted format, and is made of 10 digits starting with a zero, then we rewrite it to the desired format and we update the phone input field accordingly.

jQuery.validator.addMethod("myPhoneNumberValidator", function(value, element) {
    // no phone number is a good phone number (the field is optional)
    if (value.length == 0) { return true; }
    // if the phone number field is not empty, it has to follow the fixed format
    if(!/^33 \(0\)\d \d\d \d\d \d\d \d\d$/i.test(value)) {
        // ten digits starting with zero
        if (/^0(\d)(\d\d)(\d\d)(\d\d)(\d\d)$/.test(value)) {
            value = value.replace(/^0(\d)(\d\d)(\d\d)(\d\d)(\d\d)$/, "33 (0)$1 $2 $3 $4 $5");
            $(element).val(value); // also update the form element
            return true;
        }
    }
    return /^33 \(0\)\d \d\d \d\d \d\d \d\d$/i.test(value);
}, 'Please enter your phone number in the following format: <i>33 (0)1 23 45 67 89</i>');

Validation de formulaire jQuery avancée (1) : vérifier le format d'un numéro de téléphone (in French)
Validación de formulario jQuery avanzado (1): como verificar el formato de un número de teléfono (in Spanish)
Validação de formulário jQuery avançado (1): como verificar o formato de um número de telefone (in Portuguese)

No comments:

Post a Comment