1

I want to validate that my input is either UUID or "LAST_QUESTION". I created a custom validation rule LastOrUUID and I would like to use UUID validation rule inside of it. I could not find any way to do that, maybe you know what is the right way to implement this? My custom rule for context:

class LastOrUUID implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {

        if ($value === 'LAST_QUESTION' /* || this is uuid */) {

            return true;

        }

        return false;

    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        // TODO - add translation
        return 'This should either be the last question or have a reference to next question!';
    }
}
2
  • 1
    I think do you mean inherit default validation in you custom class!!! Commented Jun 29, 2020 at 20:58
  • @Nazari yes, that would be ideal. But I am pretty happy with at least using Str::isUuid(), if it is used by Laravel and there is no better way. Commented Jun 30, 2020 at 17:08

1 Answer 1

3

If you just want to validate if the given value is an UUID you can either Laravel's native Str::isUuid method (which uses RegEx under the hood), the isValid method of Ramsey's UUID package or plain RegEx (according to this answer):

// Laravel native
use Illuminate\Support\Str;

return $value === 'LAST_QUESTION' || Str::isUuid($value);

// Ramsey's package
use Ramsey\Uuid\Uuid;

return $value === 'LAST_QUESTION' || Uuid::isValid($value);

// RegEx
return $value === 'LAST_QUESTION' || preg_match('/[a-f0-9]{8}\-[a-f0-9]{4}\-4[a-f0-9]{3}\-(8|9|a|b)[a-f0-9]{3‌​}\-[a-f0-9]{12}/', $value);
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I know, thanks for your answer! But my thinking is - if there is a laravel rule, it must have been implemented somehow and should be reusable, no? It would be a good practice to use same UUID validation implementation everywhere where I validate UUID, am I wrong?
Good thinking! There is indeed a UUID validation rule available. It uses Str::isUuid internally which again is based on a RegEx. I'll add that to my post, because I didn't know that Laravel offers this method.
Thanks! I like this solution more. Very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.