I am using is_float()
to check if the number entered is float or not but it keeps throwing the echo()
message when I enter 3.00
. Is there any other solution to it? Or am I doing anything wrong?
Here is my code:
PHP:
if(!is_float($_POST["gpa"])){
echo "GPA must be in #.## format.";
}
HTML:
<input type="text" name="gpa" />
Form inputs are always a string, so the if condition will always return the error message you specified. Make use of filter_var()
instead.
if(filter_var($_POST['gpa'], FILTER_VALIDATE_FLOAT) === false) {
echo "GPA must be in #.## format.";
}
If you want to validate the format you need to use Regular Expressions.
([0-9]{1,})\.([0-9]{2,2})
You could use RegEx alone and forget about filter_var()
, since it does the same.
if(preg_match('/([0-9]{1,})\.([0-9]{2,2})/', $_POST['gpa']) == 0) {
echo "GPA must be in #.## format.";
}