phpvalidationrespect-validation

php respect validation just validate if not empty


I'm using php respect validation. https://github.com/Respect/Validation

class UserValidator implements iValidator
{

    public function validate($object)
    {

        $userValidator = v::attribute('email', v::email())
            ->attribute('mobile', v::numeric()->length(10,12))
            ->attribute('firstName', v::stringType()->length(5,255))
            ->attribute('lastName', v::stringType()->length(5,255))
            ->attribute('userName', v::stringType()->length(5,255)->unique('users'))
            ->attribute('password', v::stringType()->length(8,16));

        $userValidator->assert($object);

    }

}

and this is my user validation code.

username and password are only required fields. I want them to be required and other field validation should be applied only if user has filled in the input. what should I do ? after all I've implemented my own rule (unique) if it's necessary I'm ready to develop new rules or whatever. also if you know better php package for input validation I'm all ears.


Solution

  • I have not used this validation package. This may not be the best possible answer, but this is what I get from the package documentations.

    I think method oneOf() would help you, as it acts as an OR operator. The other method that would help, is nullType() which validates if the input is null. you can group what you have with nullType() to make the field optional.

    class UserValidator implements iValidator
    {
    
        public function validate($object)
        {
    
            $userValidator = v::attribute('email', v::email())
                ->attribute('mobile', v::oneOf(
                    v::numeric()->length(10,12),
                    v::nullType
                ))
                ->attribute('firstName', v::oneOf(
                    v::stringType()->length(5,255),
                    v::nullType
                ))
                ->attribute('lastName', v::oneOf(
                    v::stringType()->length(5,255),
                    v::nullType
                ))
                ->attribute('userName', v::stringType()->length(5,255)->unique('users'))
                ->attribute('password', v::oneOf(
                    v::stringType()->length(8,16),
                    v::nullType
                ));
    
            $userValidator->assert($object);
    
        }
    
    }
    

    I haven't test it, but I think it'd work.