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:
App::before(function($request) { if('POST' == Request::method()) { Input::merge(strip_commas(Input::all())); } });
This way I’ve called the helper function on every <code>POST</code> request and here is the helper function:
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] = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); } else { $result[$key] = trim($value); } } return $result; }
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
// Put this in App::before filter Input::merge(array_filter(Input::all()));
You may also like this answer on StackOverflow
.