Home > front end >  String Length validation php form
String Length validation php form

Time:09-17

This is my code to check if the field is empty and it works fine, however i want to check for both, if its empty and if its got less than 10 characters

<pre>
        if(empty($_POST['comments'])){ $errors[]="Please enter a comment."; }
</pre>

I tried this

<pre>
        if(empty($_POST['comments'])){ $errors[]="Please enter a comment."; }
        if(strlen($_POST['comments']) > 10){ $errors[]="Please enter a comment."; }
</pre>

However this then made neither work so i tried which had the same result with neither of them working

<pre>
        if(empty($_POST['comments']) && strlen($_POST['comments']) > 10)){ $errors[]="Your 
         comment must be longer than 10 characters."; }
</pre>

I have tried mb_strlen as well but that changed nothing.

CodePudding user response:

Your logic is a bit off. You're currently adding the error if the string is empty and longer than 10 characters (which would be a paradox.)

You need to check if the string is empty or less then 10 characters.

Try this:

if (empty($_POST['comments']) || strlen($_POST['comments']) < 10) {
    $errors[] = "Your comment must be longer than 10 characters.";
}

That condition checks if the string is either empty or if the string has less < than 10 characters.

&& means and
|| means or
< means less than
> means greater than

You can read more about logical and comparison operators in the manual.

  • Related