Tuesday 12 February 2013

Centralising Regular Expressions

Regular expressions are exceptionally useful and learning how to read and write them is an invaluable skill set. When creating a website you will often find yourself using the same expression in multiple locations. For example, on one website I help maintain the username is validated on four separate scripts. Without centralisation if we wanted to change the rules for the username we would have to open all four scripts and update the expressions to the new rules. With centralised expressions, we can open one script and change one expression to have the changes apply throughout the site. And we don't have to remember from which locations the username is being validated either, we just need to know we are using the correct method to validate it. I'm sure no one needs convincing of the pros of centralisation though so here is how I have centralised the regular expressions.

The following class is contained within a file called 'regex.php':

class RegEx {
 
    /*** USERNAME ***/
    public static function username()
        {
            return "/^[a-zA-Z0-9](?=[\w\-.]{5,19}$)[\w\-]*\.?[\w\-]*$/i";
        }
  
    /*** EMAIL basic email checker ***/
    public static function email()
        {
            return "/^[\w][\w.-]+?(\w@)[\w\-]+\.[A-Za-z]{2,10}(\.[\w]{2,5})?$/";
        }
  
    /*** DATE FORMAT dd-mm-yyyy where - can also be / or . ***/
    public static function dateFormat()
        {
            return "~^[0-9]{1,2}[./-][0-9]{1,2}[./-]([0-9]{2}|[0-9]{4})$~";
        }
  
    /*** CURRENCY FORMAT d+.dd ***/
    public static function currencyFormat()
        {
            return "/^\d+\.\d{2}$/";
        }

    /*** FULL POSTCODE ***/
    public static function postcode()
        {
            return "/^(?=[a-z0-9 ]{6,8}$)[a-z]{1,2}\d{1,2}[a-z]? \d[a-z]{2}$/i";
        }
}

If we find ourselves needing a regular expression we include the file:

if(!class_exists('RegEx'))
    {
        include 'path/to/regex.php';
    }

Because the function is a static one we do not need to create an instance of the class. So lets say we are checking the username, what we would write is:

if(preg_match(RegEx::username(), $u_name))
    {
        //succeed
    }

If you need a new expression you simply create a new function of the format shown.

Pretty straightforward really.

No comments:

Post a Comment