pimarc
pimarc

Reputation: 4145

Php only numbers Validating function

I would like to create a validate function for numbers only, actually I have those ones that works fine, and I tried to create one myself, but it's unfortunately not working. Here are the alphanumeric and others working fine :

// Validators
private function custom($validator, $value)
{
    return call_user_func($validator, $value, $this->request, $this->id);
}

private function alphanumeric($value, $custom)
{
    return preg_match('/^(['.$custom.'a-z0-9_]*)$/i', $value);
}

private function valid_email($value)
{
    return preg_match('/^\S+@\S+\.\S+$/', $value);
}

And the one I tried to create by modifying the alphanumeric one :

private function numbers_only($value, $custom)
{
    return preg_match('/^(['.$custom.'0-9_]*)$/i', $value);
}

What's wrong with this one ?

EDIT : I also have a JS helping with the form, for alphanumeric it's :

Form.prototype.alphanumeric = function(value, custom)
{
    return !value.replace(new RegExp('['+custom+'a-z0-9_]', 'ig'), '').length;
};

What would be the JS for numeric only ?

Upvotes: 2

Views: 39616

Answers (3)

Zauker
Zauker

Reputation: 2394

In PHP, for a "only numbers" validation you can use different approaches:

  • is_int or is_integer
  • is_numeric
  • regular expressions
  • ctype_digit
  • filter_var

is_integer()

for this function these values are are not valid: "0010", "123"

is_numeric()

for this function these values are valid: 1.3, +1234e44 and 0x539

filter_var()

for this function a value as "00123" is not valid

CONSLUSION

it seems that only regex and ctype_digit work always fine.

TEST

a simple test here

Upvotes: 5

Michael Berkowski
Michael Berkowski

Reputation: 270599

If you want only numbers, remove the $custom part from the function. The /i implies case-insensitive matching, which is not relevant for numeric matches, and so can be removed.

private function numbers_only($value)
{
    return preg_match('/^([0-9]*)$/', $value);
}

The expression above will match zero or more numbers, so blank input is allowed. To require at least one number, change * to + as in

return preg_match('/^([0-9]+)$/', $value);

And the [0-9]+ can be abbreviated as \d+. Since you are not capturing the value inside a an array of matches, there is no need for the extra overhead which is added by including the () capture group. That can be omitted as well.

return preg_match('/^\d+$/', $value);

Or skip the regex entirely...

Finally, if you've gotten this far and are matching only integers, it is far easier and less resource-intensive to just do:

// If you really intend to match numbers only, and not all numeric values
// which might include .,
function numbers_only($value)
{
  return ctype_digit(strval($value));
}

Upvotes: 7

Johannes Klauß
Johannes Klauß

Reputation: 11020

Use

is_numeric($value);

return is true or false

Upvotes: 15

Related Questions