Jump to content
Larry Ullman's Book Forums

Validate Textarea User Input

Recommended Posts

I have a contact form on my site.  I'm using the book's methods to validate POST data from a textarea input field called "contact_info". 




if (empty($_POST['contact_info'])) {

     $contact_errors['contact_info'] = 'Please enter a comment.';

} elseif (preg_match('/^[A-Za-z0-9.,-$?!]*$/', $_POST['contact_info'])) {

     $_POST['contact_info'] = str_replace(' ','',$_POST['contact_info']); //remove all spaces

     $_POST['contact_info'] = trim($_POST['contact_info']); //remove any space before or after any characters

     $_POST['contact_info'] = escape_data($_POST['contact_info'], $dbc);

     // add htmlspecialchars ???

     // anything else ???

} else {

     $contact_errors['contact_info'] = 'Your comment contains inappropriate characters.  Allowable characters include letters a to z, letters A to Z, numbers 0 to 9, as well as, period, comma, exclamation mark, question mark, dollar sign and hyphen.';





<form method="post" accept-charset="utf-8">


<?php create_contact_form_input('contact_info', 'textarea', $contact_errors); ?>






What is the most secure way to validate user input from a textarea field?


Link to comment
Share on other sites

  • 4 weeks later...
  • 11 months later...
  • 3 weeks later...
  • 1 month later...

So sorry AGAIN for the delayed reply! This got lost on my end. It's important to differentiate between "validate" and "sanctify".  It's also important to think about how you want to handle invalid data. The most crucial step is to strip out any code, using strip_tags(), before the comments might be displayed on a web page. This will protect you from code injections but doesn't raise errors to the user. Which is fine, depending upon what you want to accomplish.


If you do want to validate the data and possibly show the error to the user, then a whitelist approach of what is a valid comment is probably not going to work as there are too many characters that could be valid. I'd go with a blacklist approach instead, knowing that there's not really a good reason for a comment to include , and those are dangerous. 


Regardless of whether you validate or not, though, you'll still need to strip tags from it and make sure it's safe to use in queries (using an escaping function or prepared statements).

Link to comment
Share on other sites


  • Create New...