如果嵌套在内,如果不工作

时间:2014-04-19 18:40:07

标签: php

所以我将if语句嵌套在另一个语句中以用于表单验证,遗憾的是它不起作用。假设我使用无效的电子邮件,它只是转到一个空白页面,这告诉我它没有通过它阅读。这是我的代码看起来像

// Verification

if (empty($name && $username && $email && $pass1 && $pass2))
{
echo "Complete all fields";

// Password match

if ($pass1 <> $pass2)
    {
    echo $passmatch = "Passwords don't match";

    // Email validation

    if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
        {
        echo $emailvalid = "Enter a  valid email";

        // Password length

        if (strlen($pass1) <= 6)
            {
            echo $passlength = "Password must be at least 6 characters long";

            // Password numbers

            if (!preg_match("#[0-9]+#", $pass1))
                {
                echo $passnum = "Password must include at least one number!";

                // Password letters

                if (!preg_match("#[a-zA-Z]+#", $pass1))
                    {
                    echo $passletter = "Password must include at least one letter!";
                    }
                }
            }
        }
    }
}

很抱歉,代码有点乱,我还在努力。提前致谢。

1 个答案:

答案 0 :(得分:0)

这不会像您认为的那样起作用:

empty($name && $username && $email && $pass1 && $pass2)

你需要在每一个上使用空。

还有一些其他项目,你不需要嵌套if。怎么样?

// Verification

if (empty($name) || empty($username) || empty($email) || empty($pass1) || empty($pass2))
{
echo "Complete all fields";
// you can stop it here instead of putting the curly brace ALL the way at the bottom :)
return;
}

// Password match
if ($pass1 <> $pass2)
{
    echo $passmatch = "Passwords don't match";
}

// Email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo $emailvalid = "Enter a  valid email";
}

// Password length
if (strlen($pass1) <= 6)
{
    echo $passlength = "Password must be at least 6 characters long";
}

// Password numbers
if (!preg_match("#[0-9]+#", $pass1))
{
    echo $passnum = "Password must include at least one number!";
}

// Password letters
if (!preg_match("#[a-zA-Z]+#", $pass1))
{
    echo $passletter = "Password must include at least one letter!";
}

这样,您可以一举告诉用户所有这些问题。为什么让他们犯了一个错误,重新提交,然后发现他们犯了另一个他们不知道的错误?