1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Easy way to validate multiple fields of same content

Discussion in 'PHP' started by ian_ok, Jul 25, 2006.

  1. #1
    I have multiple fields in my form and the input can only be any number from:

    0 to 20

    I'm trying the following without any success
    function validate_qty($t) {
      $forbidden = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20');
      foreach ($forbidden as $p)
        if (strpos($t, $p) !== false) return true;
      return false;
    }
    
    Code (markup):
    with this
    
    elseif (!validate_qty($_POST['pr1'])) {
      	echo "You can only enter a number (0 to 20) in the quantity field<br>";
        echo "<a href='javascript:history.back(1);'>Click here to return</a>";
    }
    elseif (!validate_qty($_POST['pr2'])) {
      	echo "You can only enter a number (0 to 20) in the quantity field<br>";
        echo "<a href='javascript:history.back(1);'>Click here to return</a>";
    }
    
    Code (markup):

     
    ian_ok, Jul 25, 2006 IP
    nevetS likes this.
  2. ccoonen

    ccoonen Well-Known Member

    Messages:
    1,606
    Likes Received:
    71
    Best Answers:
    0
    Trophy Points:
    160
    #2
    looks like you are doing a binary compare !== and declaring the array with string items. make sure you are comparing the correct datatype to datatype when using binary compare.
     
    ccoonen, Jul 25, 2006 IP
    nevetS likes this.
  3. nevetS

    nevetS Evolving Dragon

    Messages:
    2,544
    Likes Received:
    211
    Best Answers:
    0
    Trophy Points:
    135
    #3
    why not
    
    function validate_qty($i){
     if((int)$i > 0 OR (int)$i <20) return true;
     return false;
    }
    
    PHP:
     
    nevetS, Jul 25, 2006 IP
  4. clancey

    clancey Peon

    Messages:
    1,099
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    0
    #4
    On the right track, but this will ensure a number between 0 and 20 and reject non-numeric input.

    
    function validate_qty($i)
    {
    if( preg_match( '![^0-9]!', $i) ) return false;
    if( $i >= 0 and $i <21) return true;
    
    return false;
    }
    
    Code (markup):
     
    clancey, Jul 25, 2006 IP
  5. ian_ok

    ian_ok Peon

    Messages:
    551
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks clancey, works a treat.

    Ian
     
    ian_ok, Jul 26, 2006 IP