To validate input date, both form URL or from a form, which technique do you usually use?
I have been looking at PHP Filters but i have rarely see them on any code.
I have usually seen the use of preg_mach, for example:
$numbers = "/^[0-9]+$/D";
if (preg_match($numbers, $var)){
echo "is number";
}
Instead of:
if(!filter_var($var, FILTER_VALIDATE_INT))
echo "is number";
}
Is there any advantage using one or another? Thanks!
My two cents: It depends.
It depends on the situation on whether you should use the filter functions over a regex. Actually, the criteria is pretty simple:
Is there a filter_*
function that exists that validates exactly the kind of input I'm expecting?
filter_*
function.Regexs are more complex than the filter_*
functions, but the functionality of filter_*
and regexs are very loosely correlated. Most likely, a regex can be crafted to do the job of a filter_*
function, but it doesn't work the other way around. So, regexes bring increased functionality and flexibility to the table while also being more complex.
Personally, when dealing with simple inputs (integers, dates, times), I use a filter_*
function, while more complex inputs or very specific or custom inputs (custom identifier that should start and end with a letter and have 3 digits in between) are more suited for a regex.
Php introduced the filer_ functionality for a wide range of types of variable validation since php 5.2. It's good practice to use the filter_var || filter_input for your needs.
Besides the fact that it's safer it will also save you lots of development time cracking your head over regular expressions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With