Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


PHP textarea validation

Hello me again, I hope someone can help, I'm quite new to php so this may be quite simple but im pulling my hair out. I have spent the last 3 days google'in around with no such luck.

Basically I have a textarea which gets written to file on submit. I would like to add some validation before the textarea gets submitted.

I would like to check the whole textarea for certain words and then echo back an error message if the word isn't aloud.

for example if the user enters the word "dog" echo "Dog isnt alound".

Also I would like to able to check if one word is listed then the text area must contain another world before its allowed.

for example of the users enters "Cat" echo "you must have ginger with cat"

text area contains the worlds "ginger" and "cat" - it gets submitted.

I hope that all made scenes. please help!!

1 Answer

Randy Hoyt
Randy Hoyt
Treehouse Guest Teacher

I would first recommend checking out my videos on the contact form for the Shirts 4 Mike website. That will show you how to set up a form and put some validation in place.

After that, you'll want to use various string functions to perform the validation. The value from the textarea needs to be loaded into a variable. You can check if the textarea contains certain pieces of text using the strpos function.

You'll want to write nested conditionals. Here's an example of the flow (this isn't all real code, but a text description):

$message = [text area value];
if ([$message contains dog]) {
    echo "You cannot use the word dog.";

if ([$message contains cat]) {
    if ([$message does NOT contain ginger]) {
    echo "You can only use the word cat if you also use the word ginger.";

// the data is valid; do something with it