简体   繁体   中英

Error with the Validation Code

I have the following validate method in my Validation Class:

public function validate($data, $rules)
{
    if(!is_array($rules))
    {
        $rules = array($rules);
    }
    foreach($rules as $rule)
    {
        if(is_array($rule))
        {
            if(!$this->{$rule[0]}($data, $rule[1]))
            {
                array_push($this->errors, $rule[0] . ' is ' . $rule[1]);
                $ruleValue = $rule[0];
                print_r($this->errorMessages[$ruleValue] . BR);
                return $this->errors;
            }
        }
        else
        {
            if(!$this->{$rule}($data))
            {
                array_push($this->errors, $rule);
                print_r($this->errorMessages[$rule] . BR);
                return $this->errors;
            }
        }       
    }
    if(empty($this->errors))
    {
        return TRUE;
    }
}

with a method that checks for valid date (ie less than the present date)

private function validDate($data)
{
    $now = date('Ymd');
    return ($data < $now) ? TRUE : FALSE;
}

I have another php file which creates this Validation class and then checks for input and validates it:

if
            (
                $Validation->validate($email, array('required', 'isEmail')) &&
                $Validation->validate($password, array('required', array('min_length', '6'), array('max_length', '20'))) &&
                $Validation->validate($repeatPassword, array('required', array('min_length', '6'), array('max_length', '20'), array('matches', Input::fetch('password')))) &&
                $Validation->validate($date, array('required', 'validDate'))
            )
{
   echo 'Yes';
}

Now, ideally, the echo code should be executed when all validations are true and it worked fine before I made changes to the valid Date method in the Validation class.

It prints the error which means it returns false but the message 'Yes' is being echoed as well.

I have used && in the if statement which means if any one condition is false, the code wouldn't be executed but I can't seem to understand why it is running when all conditions return false.

You are returning

return $this->errors;

in your validate function. But it's definitelly not false or 0, so it is true and it pass through your condition. You shoud return false

The method validate always returns something different to false, so the if expression is always true. This way, you get the error, and also the "Yes" output. I suggest you to make the method to return true or false, according to the validation, and set the errors as a public attribute, so you can read them in case of a false validation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM