I have a description column in database which is JSON, with KeyValue component I add data, but the problem is that I could not implement the rule for key values, I want each key and value be between 3 and 30 characters.
KeyValue::make('description')
->label('description')
->keyLabel('key')
->valueLabel('value')
->addActionLabel(__('Add Feature'))
->default([]),
You can solve this first creating a custom Rule, something like the following:
<?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class JsonKeyValueLength implements ValidationRule
{
/**
* Run the validation rule.
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
foreach ($value as $key => $val) {
if (strlen($key) < 3 || strlen($key) > 30 || strlen($val) < 3 || strlen($val) > 30) {
$fail('The length of keys and values should be between 3 and 30.');
}
}
}
}
Then, after creating this rule, you can use it by chaining the rules method it on the KeyValue component as following:
KeyValue::make('description')
->rules([new \App\Rules\JsonKeyValueLength()])
->label('description')
->keyLabel('key')
->valueLabel('value')
->addActionLabel(__('Add Feature'))
->default([]),