0

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!';
    }
}
Danielius
  • 852
  • 5
  • 23
  • 1
    I think do you mean inherit default validation in you custom class!!! – Nazari Jun 29 '20 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. – Danielius Jun 30 '20 at 17:08

1 Answers1

2

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);
Dan
  • 5,140
  • 2
  • 15
  • 30
  • 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? – Danielius Jun 29 '20 at 16:53
  • 1
    Good thinking! There is indeed a UUID validation rule available. It uses [`Str::isUuid` internally](https://github.com/laravel/framework/blob/cb398188729f51e63d6fd0dc1ed9009fcf76b404/src/Illuminate/Validation/Concerns/ValidatesAttributes.php#L1771) which again is based [on a RegEx](https://github.com/laravel/framework/blob/cb398188729f51e63d6fd0dc1ed9009fcf76b404/src/Illuminate/Support/Str.php#L290). I'll add that to my post, because I didn't know that Laravel offers this method. – Dan Jun 29 '20 at 16:58
  • Thanks! I like this solution more. Very helpful. – Danielius Jun 30 '20 at 09:26