Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End How to not submit form with random spaces or without text?

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #169226
    chrisburton
    Participant

    I’m trying to figure out how to not allow my comment form to be submitted if someone just puts a space(s) or just hits submit.

    This is what I have so far and it does not seem to be working.

    if(empty($comment)) {
        echo '<div style="color:red">No blank comments allowed.</div>';
    } else {
        $insert = db::insert('comments',
            array(
                'id'=>NULL,
                'uid'=>$user['uid'],
                'comment'=>$comment,
                'article_id'=>$article_id,
                'date'=>'NOW()',
            )
        );
    }
    
    #169243
    __
    Participant

    And on the PHP side, you can use the trim function:

    $comment = trim( $comment );
    if( empty( $comment ) ){
        /* no empty comments allowed! */
    }
    
    #169244
    shaneisme
    Participant

    Yeah, PHP empty will return false with a string that is spaces only.

    I normally have a method that scrubs a few basics on user inputs to stop things like XSS or blank fields on any POST or GET.

    This is not very “performant”, or very clean, but maybe it’ll give you an idea:

    function cleanup($n) { 
      if (is_array($n)) {
        return array_map('cleanup', $n);
      } else {
        $n = trim($n);
        $n = htmlspecialchars($n);
        return $n;
      }
    }
    if (!empty($_POST)) { // This will call cleanup for all user inputs
      $_POST = array_map('cleanup', $_POST);
    }
    

    This way, every time a users POST‘s a form the data will get scrubbed before it reaches your checks (assuming you do this immediately in order of operation).

    #169299
    chrisburton
    Participant

    Thanks @TheDoc, @shaneisme and @traq. trim() worked well.

Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘Back End’ is closed to new topics and replies.