mercredi 14 octobre 2015

Laravel 5.1: custom validation with custom error message

I have custom validation which I added to my form request as:

public function rules()
{
    return [
        ...
        "firstCheckbox" => "required_with_one_of:secondCheckbox,thirdCheckbox",
        ...
    ];
}

Rule is that if the user selects firstCheckbox then he needs to select at least one more checkbox from given parameters: secondCheckbox or thirdCheckbox.

To make this happen I added to AppServiceProvider.php's boot function following code:

    Validator::extend('required_with_one_of', function($attribute, $value, $parameters, $validator)
    {
        $data = $validator->getData();
        foreach ($parameters as $p) {
            if ( array_get($data,$p) != null) {return true;}
        }

        return false;
    });
    Validator::replacer('required_with_one_of', function($message, $attribute, $rule, $parameters) {
        return str_replace(':values', implode(' / ', $parameters), $message);
    });

All of this is working fine but if I'm not thinking of something please point it out so I can fix it.

My real problem is with the message. The message I receive is:

"You must select at least one of the fields: secondCheckbox, thirdCheckbox"

But what I want is to get message:

"You must select at least one of the fields: Second Checkbox, Third Checkbox"

To my lang\en\validation.php attributes[] I have added

'secondCheckbox' => 'Second Checkbox'

'thirdCheckbox' => 'Third Checkbox'

values, but this doesn't work because I never replace $parameters values in the Validator::replacer().

I have looked at Validator class and there is simple function that handle all of this

$parameters = $this->getAttributeList($parameters);

but I can't call that from Validator::replacer().

Is there a simple way to call this function from Validator::replacer() or should I just create CustomValidator class extending the Validator.

If the second way is the way to go can someone give me instructions how to do this. I've never really used PHP at this level so, although I have rough idea what to do, I'm not really sure how to do this.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire