限制两个限制之间的字符数

时间:2012-12-27 16:59:58

标签: php validation if-statement error-handling

我有一个验证if语句,主要检查两件事。第一:查看名为“why”的下拉框是否为空,如果为空,则会向前端发出错误,说明我们需要您给出正确的理由。这很好。现在我有第二个条件,如果由于任何原因,“为什么”下拉框中的值是“其他”,如果注释框为空,则会发出另一个错误。现在这两个工作正常,如果它是空的会说“请在评论栏中解释您访问的性质!”

我的问题是我想要它,以便评论框的长度在15到45个字符之间。我一直在使用这个signinpage.php验证大约20个小时,以使它完全符合我的要求,我无法到达我想要的地方。任何帮助都很可爱!

if(empty($why)) {
            $errors[] = 'Please make sure to select the proper reasoning for your vistit today!';
    } 
        elseif ($why ==='Other' && empty($comments)) {
            $errors[] = 'Please explain the nature of your visit in the comments box!';

        if (strlen($comments) < 15) {
            $errors[] = 'Your explaination is short, please revise!';
    }
        if(strlen($comments) > 45) {
            $errors[] = 'Your explaintion is to long, please revise!';
    }
    }

缩进的:

if(empty($why)) {
    $errors[] = 'Please make sure to select the proper reasoning for your vistit today!';
} 
elseif ($why ==='Other' && empty($comments)) {
    $errors[] = 'Please explain the nature of your visit in the comments box!';

    if (strlen($comments) < 15) {
        $errors[] = 'Your explaination is short, please revise!';
    }
    if(strlen($comments) > 45) {
        $errors[] = 'Your explaintion is to long, please revise!';
    }
}

2 个答案:

答案 0 :(得分:0)

如果您正确地复制并粘贴了这个,那么您的括号会搞乱。将您的所有评论验证放入仅在$why==="Other"

进行检查的单个部分中
if(empty($why))
    $errors[] = 'Please make sure to select the proper reasoning for your vistit today!';
elseif ($why ==='Other'){
    if(empty($comments))
        $errors[] = 'Please explain the nature of your visit in the comments box!';
    else{
        if (strlen($comments) < 15)
            $errors[] = 'Your explaination is short, please revise!';
        if(strlen($comments) > 45)
            $errors[] = 'Your explaintion is to long, please revise!';
    }
}

答案 1 :(得分:0)

if(empty($why)) {
        $errors[] = 'Please make sure to select the proper reasoning for your vistit today!';
} 
elseif ($why ==='Other' && empty($comments)) {
        $errors[] = 'Please explain the nature of your visit in the comments box!';
}
elseif($why === 'Other'){
    if (strlen($comments) < 15) {
        $errors[] = 'Your explaination is short, please revise!';
    }
    if(strlen($comments) > 45) {
        $errors[] = 'Your explaintion is to long, please revise!';
    }
}

您在检查中包含了对长度的检查,要求注释为空。