1
Php

Laravel Tips – Automatic Input Filtering

Todays topic is about how to filter user inputs automatically to remove commas (thousand separator) before validating. Going to share the way I solved the problem. So, a few days ago I was working on a project of mine where I had to develop a web based accounting software for a travel agent. So I’ve used Laravel 4.2, the awesome PHP framework. In that project, the client asked me to allow automatic formatting of numeric input by using comma (thousand separator) and dot (fraction separator) and he wanted it as, when a user types in a certain input box as an amount of money, for example 10000 it should turn into 10,000.00 automatically. So, I’ve used the jQuery Autonumeric Plugin to achieve this functionality. It was not that much hard, thanks to that plugin developer, anyways.

But on the server side, I had to clean those values before validating and inserting it into the database. Without removing commas I couldn’t validate because validation would be failed. So, I had to clean those input fields every time I submit a form and save the data into the database but I was looking for a way to do it easily and automatically. So, I’ve created a helper function and called that helper function in the App::before application event. It was like:

This way I’ve called the helper function on every <code>POST</code> request and here is the helper function:

So, this way I cleaned all of my input fields that used to carry a formatted money amount. The function is not very big or complex. I’ve used PHP‘s native FILTER_SANITIZE_NUMBER_FLOAT with FILTER_FLAG_ALLOW_FRACTION flag to clean my inputs whose name was any one of these: deposit, expense, amount or price.

Quick Tip : Remove all empty input fields from Input array

You may also like this answer on StackOverflow.

  • ConradH

    here is my solution. It checks if the input is already a valid float.
    without that the filter_var turns numbers with a dot as separator into zero.

    function strip_commas($array)
    {
    $result = array();
    foreach ($array as $key => $value) {
    if(in_array($key, array(‘deposit’, ‘expense’, ‘amount’, ‘price’))) {
    $value = trim($value);
    $result[$key] = nummer_filter($value);
    }
    else {
    $result[$key] = trim($value);
    }
    }
    return $result;
    }

    function nummer_filter ($nummer)
    {
    if(filter_var($nummer,FILTER_VALIDATE_FLOAT) === false){
    $nummer = filter_var($nummer, FILTER_VALIDATE_FLOAT, array(‘options’ => array(‘decimal’ => ‘,’), ‘flags’ => FILTER_FLAG_ALLOW_THOUSAND));
    }else{
    return filter_var($nummer,FILTER_VALIDATE_FLOAT);
    }
    return $nummer;
    }

Latest Blog