3
votes

I use proengsoft/laravel-jsvalidation in combination with a custom FormRequest and custom validation rules that I defined via Validator::extend(...) in a service provider. This works well.

However, when I port my custom rules to the new(ish) custom Rule class in Laravel 5.5+, JsValidator fails at getting my custom Rule messages.

I have this custom rule:

use Illuminate\Contracts\Validation\Rule;

class MyRule implements Rule 
{
    public function passes($attribute, $value) {
        return $value > 10;
    }
    public function message() {
        return 'Your :attribute is pretty small, dawg!';
    }
}

My form request uses this rule:

use Illuminate\Foundation\Http\FormRequest;
use App\Rules\MyRule;

class MyRequest extends FormRequest 
{
    public function authorize() {
        return true;
    }
    public function rules() {
        $rules = [
            'foo' => 'required|numeric',
            'bar' => ['required', new MyRule()],
        ];
        return $rules;
    }
}

This should work, but I get thrown an Exception on

{!! JsValidator::formRequest('\App\Http\Requests\MyRequest') !!}

An Exception is thrown from a call to Str::snake(Object(App\Rules\MyRule)) made by Proengsoft\JsValidation\Javascript\MessageParser.php.

JsValidation does not look at the $rule object type before calling Validator->getMessage($attribute, $rule) where instead it should be calling $rule->messages();

Can I work around this bug somehow, and use laravel-jsvalidation together with my custom Rule and FormRequest -- or does it necessarily require i make a pull request and hope it will be fixed... someday? I'd like to make this work now-ish.

1

1 Answers

0
votes

This can be archived by passing JsValidator instance based on rules and message arrays instead of passing the form request. In controller Pass this instance to blade. Read here for more details.

JsValidator::make($rules, $messages, $customAttributes, $selector)

In controller,

$validator = JsValidator::make(
    [
        'name' => 'required',
    ],
    [
        'name.required' => 'Name field is a required field',
    ]
)

return View::make("Your view", compact($validator));

In blade,

{!! $validator->selector('.wizard_frm') !!}

<form class='wizard_frm'></form>

And in this case we can create object of request class and pass rules function returned array to JsValidator::make if needed.