首页 > 解决方案 > 字符串长度验证php表单

问题描述

这是我检查该字段是否为空并且工作正常的代码,但是我想检查两者,如果它是空的并且它是否少于 10 个字符

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

我试过这个

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

然而,这两个都没有工作,所以我尝试了相同的结果,但他们都没有工作

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

我也尝试过 mb_strlen ,但这并没有改变。

标签: phpformsvalidation

解决方案


你的逻辑有点不对劲。如果字符串为空且长度超过 10 个字符,您当前正在添加错误(这将是一个悖论。)

您需要检查字符串是否为空或少于10 个字符。

试试这个:

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

该条件检查字符串是否为空字符串是否少于<10 个字符。

&&手段
||手段
<手段小于
>手段大于

您可以在手册中阅读有关逻辑比较运算符的更多信息。


推荐阅读