Monday, November 11, 2013

Client + Server Side Validation = New Love

Having to do some recent form validation I wanted to have a solution that worked both on the client and server side. I found it!

It comes from combining jQuery Validation Plugin and jQuery Validation PHP Plugin

Using both of these libraries I create one rule file and incorporate it for both client and server side validation. My recent rule file looks like the following.

<?php
    $validation_rules = array(
        'rules' => array(
            'timestamp' => array(
                'required' => true,
                'number' => true
            ),
            'full-name' => 'required',
            'address' => 'required',
            'city-state-zip' => 'required',
            'home-phone' => 'required',
            'email' => array(
                'required' => true,
                'email' => true
            ),
            'birthday' => array(
                'required' => true,
                'dateUS' => true
            )    
        ),
        'messages' => array(
            'timestamp' => array(
                'required' => 'Select a date.',
                'number' => 'The date selected is not valid.'
             ),
            'full-name' => 'Enter your full name.',
            'address' => 'Enter your address.',
            'city-state-zip' => 'Enter your city state and zip.',
            'home-phone' => 'Enter a phone number.',    
            'email' => array(
                'required' => 'Enter your email address',
                'email' => 'Enter a valid email address'
            ),
            'birthday' => array(
                'required' => 'Enter your birthday',
                'dateUS' => 'Enter a date in the format mm/dd/yyyy.' 
            )
        )
    );
?> 

Notice how I have dateUS. That is a custom validation rule I set up. Adding custom rules is really easy for both libraries.

I am using Twitter Bootstrap for my framework, and the following js helps jQuery validator work great on the client side.

var settings = $('#form').validate(<?php echo json_encode($validation_rules); ?>).settings;
$.extend(settings, {
    errorClass: 'help-block',
    highlight: function(element){
        $(element).closest('.control-group').addClass('error');
    },
    success: function(element){
        element.closest('.control-group').removeClass('error');
    }
});

My post to page now follows something along the following logic.

<?php 
    require_once 'rules.php'; 
    require_once 'validator.class.php'; 

    $oValidator = new Validator($validation_rules);

    $validated_data = $oValidator->validate($_POST);

    if (count($validated_data) == 0){
        echo 'no errors';
    }
    else{
        print_r($validated_data);
    }
?>