1

I have an HTML5 form to collect data and one of the inputs is for a phone number. I am using php to validate all the data the user enters. I want to validate that the user entered only numbers (from 0 to 9) using the preg_match() function. I am using "/[^0-9]/" as the regex pattern but for some reason it only allows characters (from a to z) to be validated. Why would this happen ?

Mikey
  • 345
  • 5
  • 9
  • 15

4 Answers4

0

'^' indicates the beginning of the string only when it's the first character. Otherwise it means "not". So your expression is matching anything not a number (Carets in Regular Expressions).

The correct expression would be '/^[0-9]*$/' as mentioned in the other answer.

Community
  • 1
  • 1
Jonathon Klem
  • 258
  • 4
  • 19
0
function num_only($num){
 // will return only numbers in a string
  return preg_replace("/[^0-9,.]/", "", $num);
}

function numeric($num){
    // will check if is numeric
    $int = $num;
    if(empty($int) or strcmp(preg_replace("/[^0-9,.]/", "", $int), $num) != 0 )
    {
        return false;   

    }
    else return true;
}

// will check if string is numeric

is_numeric($number);
SyntaxError
  • 27
  • 2
  • 3
  • 9
-1

try this instead: '/^[0-9]*$/'

ElefantPhace
  • 3,806
  • 3
  • 20
  • 36
-1

Try this :

/[0-9]+/

It matches any digits.

Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
  • 1
    This works, but why not use the shorthand `\d+` instead? Or even more explicitly - `[:digit:]`. – Amal Murali Mar 01 '14 at 21:20
  • @AmalMurali `\d` matches `[0-9]` **and** other digits like `Eastern Arabic numerals`. Since the question is about *only* digits from 0 to 9, it is more appropriate here to have `[0-9]` – Justin Iurman Mar 01 '14 at 22:03
  • @Dr.Kameleon you should use `^ $` delimiter. Otherwise, your pattern could also match **abc012345xyz** and this is not what OP wants – Justin Iurman Mar 01 '14 at 22:06