Rabu, 23 Januari 2008

PHP functions to validate Integer, Float and characters length input

Sometimes we need to validate an input from client browser before we push the value into further proccess, here i share 3 simple functions to perform validation input from forms and or querrystrings

Validate Integer Value Using isNumeric function

function isNumeric($n){
return ( $n == strval(intval($n)) )? true : false;
}

the simple php function above will perform an integer validation input, the proccess is pretty simple, the if control structure will evaluate whether the argument value ($n) has the same type with itself after cast to integer (strval(intval($n))), the right part of if expression (strval(intval($n))) is a simple way to cast any type of variable into integer. Sample of usage:

echo
isNumeric(1) = ‘
.(string)isNumeric(1);
echo
isNumeric("a") = ‘
.(string)isNumeric(‘a’);
echo
isNumeric(0.1) = ‘
.(string)isNumeric(0.1);

Validate Float Value Using isFloat function

function isFloat($n){
return ( $n == strval(floatval($n)) )? true : false;
}

the simple php function above has same proccess with isNumeric function the difference is only the second part of if expression (strval(floatval($n))) which has function to cast the value of argument into floating point variable. Sample of usage:

echo
isFloat(1) = ‘
.(string)isFloat(1);
echo
isFloat("a") = ‘
.(string)isFloat(‘a’);
echo
isFloat(0.1) = ‘
.(string)isFloat(0.1);

Validate Characters Length Using isLength function

function isLength($s,$min,$max){
$curLength = strlen($s);
return (($curLength >= (int)($min)) && ($curLength <= (int)($max)))? true : false;
}

the php function above will perform a Length of characters validation, it takes 3 arguments which are (string_to_be_validate,minimum_length,maximum_length). Sample of usage:

echo
isLength("aku",1,4) = ‘
.isLength(‘aku’,1,4);
echo
isLength("aku",4,4) = ‘
.isLength(‘aku’,4,4);
echo
isLength("aku",3,4) = ‘
.isLength(‘aku’,3,4);

Tidak ada komentar:

Advertise