Need help with PHP Form Validation preg_match and textarea not working together

Ok, I have a form that I am trying to validate with php. It has an input boxes for a first name, last name, email and a textarea for comments. The code to validate the first three work as they should but the code to validate the textarea does not. I does validate to make sure that a comment is entered but does not validate the last condition.

And I understand that the validation could include more, but I’m just learning.

The php code is below.


$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$email = $_POST["email"];
$comment = $_POST["comment"];

/* regular expressions for first name */
 if(!preg_match("/[a-zA-Z]/", $firstname)){
    echo "<p>Please enter your first name.</p>";
 else if(preg_match("/</", $firstname)){
    echo "<p>Please enter a valid first name.</p>";

/* regular expressions for last name */
 else if(!preg_match("/[a-zA-Z]/", $lastname)){
    echo "<p>Please enter a last name.</p>";
 else if(preg_match("/</", $lastname)){
    echo "<p>Please enter a valid last name.</p>";

/* regular expressions for email */
 else if(!preg_match("/[a-zA-Z0-9.-]+@[a-zA-Z0-9]+\\.[a-z]{2,7}?/", $email)){
    echo "<p>Please enter an email.</p>";
 else if(preg_match("/</", $email)){
    echo "<p>Please enter a valid email.</p>";

/* regular expressions for comment */
else if(!preg_match("/[a-zA-Z0-9.-]/", $comment)){
    echo "<p>Please enter a comment.</p>.";
 else if(preg_match("/</", $comment)){
    echo "<p>Please enter a valid comment.</p>";

 else { }


Thank You

using your exact code, it works perfectly for me. If I enter a < in the text area it’s rejected. If the < isn’t there it passes.

Maybe there’s something not quite right with your form - this is what I used:

<form action="validate.php" method="POST">
<p><input type="text" name="firstname" value=""> </p>
<p><input type="text" name="lastname" value=""> </p>
<p><input type="text" name="email" value=""> </p>
<p><textarea rows="4" cols="50" name="comment"></textarea></p>
<p><input type="submit" name="submit" value="Submit"/></p>

Thanks for trying the code out. I got the form to work as I want it to, now I just have to fix something else that’s wrong with my page. Thanks anyway.