Regular Expressions Help

Discussion in 'PHP' started by sayyes, Jun 21, 2006.

  1. #1
    I'm having trouble validating some information that I am getting from a form. I have two textfields. One they can enter a number (3, 12, etc.). The other field is a textfield as well and they can enter a number but it must be five digits (a zip code).

    I have to do the validation in PHP on the server side because this is a drupal site.

    I'm trying to do the first one with the following code, but it isn't working.

    
    if(!preg_match("/[0-9]+/", $var)) {
          Error message
    }
    
    Code (markup):
    I've always struggled with these damn things...

    TIA
     
    sayyes, Jun 21, 2006 IP
  2. clancey

    clancey Peon

    Messages:
    1,099
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I am unsure what you are trying to do. If you want to verify that the entry contains numbers, then your test works. However, it will pass "123ab" just than same as "12345".

    If you only want numbers, but there is no set length, try

    
    if( preg_match("/[^0-9]/", $var))
         { echo "Error message\n"; }
    
    Code (markup):
    If there must be five numbers and five numbers only:

    
    if(!preg_match("/[0-9]{5}/", $var) || strlen($var) != 5)
         { echo "Error message\n"; }
    
    Code (markup):
    But, is there not another format for US postal codes?
     
    clancey, Jun 21, 2006 IP
  3. dtang4

    dtang4 Active Member

    Messages:
    303
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    58
    #3
    You should add ^ $ to make sure the entire string is filled with numbers
    e.g.
    /^[0-9]+$/
     
    dtang4, Jun 24, 2006 IP