Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regex - Value of 1 or more integers [duplicate]

Hey I'm trying to perform input validation in PHP to ensure that the stock values that are typed in are at least 1 positive integer and from 0-9. Should not contain any special characters.

For example, any of the following values should be valid:

7
0
32
47534

The following SHOULD NOT be valid:

asdf
35/gdf
../34.

etc..

I'm using the following if statement to check for the positive integer value of "$original_stock".

if (preg_match("/^[0-9]$/", $original_stock)) 
{
    $error .="Original stock must be numerical.";
}

Additionally, I have a price field which should be validated as either an int or a double.

If there's an easier alternative to using regex, that's okay too!

Thanks in advance :)

like image 236
JheeBz Avatar asked May 29 '11 06:05

JheeBz


2 Answers

Try this regexp:

/^\d+$/

The issue with your existing regexp is that it only matches strings with exactly one digit.

As for validating an int or a double:

/^\d+\.?\d*$/

Note that that regexp requires that there be at least one digit.

like image 187
Rafe Kettler Avatar answered Oct 06 '22 00:10

Rafe Kettler


Use:

/^[0-9]+$/

The + means "one or more". Without it, your regex will only match a single digit. Or you could use the simpler variant:

/^\d+$/

For floats, try something like:

/^\d+(\.\d{1,2})?/

This will match one or more digits, optionally followed by a . and one or two digits. (i.e. .12 will not match.)

To save yourself some headaches, you can also use the is_int and is_float functions.

Lastly; note that your check is wrong. preg_match will return 0 if it fails, so you should write it as:

if (!preg_match("/^\+$/", $original_stock)) {
  // error
}

(note the !).

like image 31
Mat Avatar answered Oct 06 '22 00:10

Mat