Check if user enters numbers ONLY, PHP

时间:2015-11-12 10:57:37

标签: php validation

I have this inupt field

 <p style="font-size: 18px;">Total Bids: <input type="text" class="total_bids" name="total_bids" placeholder="No. of Bids"></p>

getting its value via:

var totalbids = document.getElementsByName('total_bids')[0].value;

and getting the value in PHP via

$total_bids = PSF::requestGetPOST('totalbids');

Everything working fine, but it is supposed to take number value ONLY, so I am trying to check if user only enters a number, how can I define alphabet range so that I can set the check something like

if( $total_bids== 'alphabet range')
        {
           return json_encode(array('error' => 'Please enter a valid Number.'));
        }

5 个答案:

答案 0 :(得分:2)

You can use RegEx and the \d Expression. \d matches only numbers.

答案 1 :(得分:1)

First of all, you could disallow the person to enter anything but numbers in the <input../> by defining it's type as type="number".

Obviously, people could go around it so you still need to check it in the backend for that, you'll need to use a function like is_numeric().

答案 2 :(得分:1)

You can check by is_numeric

if(!is_numeric($total_bids))
{
    return json_encode(array('error' => 'Please enter a valid Number.'));
}

Also if you want do any special checks, you can use regexp by preg_match, for example:

if(!preg_match('~^[\d\.]$~', $total_bids))
{
    return json_encode(array('error' => 'Please enter a valid Number.'));
}

Regexp more flexible, you can add your own rules to check by regexpm but is_numeric check faster then regexp check

答案 3 :(得分:1)

as per your input if you need only numbers then try ctype_digit:

$strings = array('1820.20', '10002', 'wsl!12');//input with quotes is preferable.
foreach ($strings as $testcase) {
    if (ctype_digit($testcase)) {
        echo "The string $testcase consists of all digits.\n";
    } else {
        echo "The string $testcase does not consist of all digits.\n";
    }
}

see here :http://php.net/ctype_digit

答案 4 :(得分:1)

if(preg_match ("/[^0-9]/", $total_bids)){ 
    return json_encode(array('error' => 'Please enter a valid Number.'));
}