I'm looking for a way to check a text field to make sure only a numbers and decimals are present. The text field will be submitted via the $_POST[""] method.
I'd like to make sure only values like these are submitted.
10
20.4
19.99
0.75
I'd like to make sure these values are not submitted.
10 dollars
20 and .40
Ten Dollars
$10,000.15
I'm confused as to which of these I should use to check the variable value
ctype_digit
is_int
is_numeric
Can someone please point me in the right direction? Thank you!
Here you have to use is_numeric
because is_int
and ctype_digit
are not checking for floats, only for integers.
As pointed out in comments. is_numeric
also accepts scientific notations, binary, octal and hexadecimal.
To narrow it down to floats, int and scientific notation you should use is_float
but there still is the scientific notation, then you can add a simple check with strpos
. Final code would look like this:
def is_simple_float(x):
return is_float(x) && strpos(x, 'e') === false
The ===
means that you chack the values and the type of the variables (to ensure that if the 'e'
is at position 0 it does not return true).
if(isset($_POST['field']) && is_numeric($_POST['field']) && $_POST['field'] > 0) { }
Let's break this down.
Make sure $_POST['field']
actually exists:
isset($_POST['field'])
Exists? Good. Is it numeric?
is_numeric($_POST['field'])
Yes? Fantastic. Now it's numeric, make sure people enter positive values (if that is what you desire)
$_POST['field'] > 0
(or of course, >=
, up to you)
Let's add one more step to ensure that if it follows these rules, it's also only two decimals or less.
if(strpos($_POST['field'], '.') !== false) {
$decimals = explode('.', $_POST['field']);
if(strlen($decimals[1]) <= 2) {
//proceed
} else {
//should error
} else {
//proceed
}
I'd probably use RegEx for this...
<?php
function clean_decimal($string){
$string = !empty($string) ? $string : "10 dollars";
$string = preg_replace("/[^0-9.]/i","",$string);
return number_format(doubleval($string),2,".",",");;
}