eggplantSword's avatar

Validate same value two different ways

I'm trying to validate a password but this password comes in encoded as base64 and I also want to run Password::defaults() on the decoded base64 text.

The code is a regular validation

    public function getAuthToken(Request $request)
    {
        $request->validate([
            'password' => ['required', 'string', new isBase64, Password::defaults()]
        ]);

		// rest of code
}

This isn't working because the Password::defaults() are checking on the encoded text.

How can I do this so it checks that the password is coming in encoded as base64 but also check the decoded text with that separate rule?

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

If you are using a FormRequest, you can use the prepareForValidation to decode the password before validating.

protected function prepareForValidation(): void
{
    $this->merge([
        'password' => base64_decode($this->password),
    ]);
}

https://laravel.com/docs/11.x/validation#preparing-input-for-validation

I don't suppose the base64 encoded value is what you were interested in anyway? But if it was, you could re-encode it using the passedValidation method (see same link above)

Mega_Aleksandar's avatar

Hi,

You can also combine your custom check isBase64 with the Password:defaults() in a single check

class isBase64AndDefault implements Rule
{
    public function passes($attribute, $value)
    {
        // check base64
        $isBase64 = base64_encode(base64_decode($value, true));
        //utilize the Password::defaults()
        return Password::defaults()->passes($attribute, base64_decode($value)) && $isBase64;
    }

    public function message()
    {
        return 'The password does not meet the required complexity.';
    }
}

quick and dirty snippet (not tested) but hope it helps.

Please or to participate in this conversation.