Livewire ValidationRule for a slug.
Hello,
I'm currently exploring livewire 3 and looking into the validation aspect of it. I'm separating out my validation rules into their own FormsRequest class and then I'm using a custom Rules Class to manage validating slugs.
Basically I'm just double checking that the created slug value is actually a valid slug before submitting to the database.
In my class StorePageRequest extends FormRequest file:
public function rules(): array
{
return [
'slug' => [
'required',
Rule::unique('pages', 'slug')->ignore($this->slug),
new SlugFormat,
],
'title' => ['required'],
];
}
}
Then in my SlugFormat custom Rules class I have the following
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Str;
class SlugFormat implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
$validSlug = (string)Str::of($value)->slug('-');
if ($validSlug !== $value) $fail("$attribute " . " is not a valid slug");
}
}
I'm checking that the values don't match the correct slug format and it should fail.
This works in that it does fail when its not formatted correctly but when the slug is correctly formatted, it still fails the validation and say 'Slug is not a valid slug'.
I'm using livewire 3 page component to render my page and form.
IN my class CreatePage extends Component file:
#[Validate()]
public $title = '';
public $slug = '';
public function rules()
{
return (new StorePageRequest())->rules();
}
I'm not sure what ive done or if this is something related to livewire? Any advice would be great thanks.
Please or to participate in this conversation.