1
votes

I have created a few new validation rules for my Laravel application by following the Laravel docs https://laravel.com/docs/5.6/validation#custom-validation-rules, however, when I attempt to register the rules into my custom requests rules array, an error is thrown:

#message: "trim() expects parameter 1 to be string, object given"
#code: 0
#file: "/Users/ari/Projects/dps/sites/acg/vendor/laravel/framework/src/Illuminate/Validation/ValidationRuleParser.php"
#line: 217
#severity: E_WARNING

My custom rule - NotContainsEmail.php:

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class NotContainsEmail implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        return (strpos($value, '@') !== false);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'This field cannot contain an email address.';
    }
}

My Request - QuoteRespondRequest:

<?php namespace Client\Http\Requests\Quotes;

use App\Rules\NotContainsEmail;
use Client\Http\Requests\FormRequest;

class QuoteRespondRequest extends FormRequest
{
    public function rules()
    {
        return [
            'help' => ['string', 'nullable', new NotContainsEmail],
            'description' => ['string', 'nullable', new NotContainsEmail],
            'community' => ['string', 'nullable', new NotContainsEmail],
            'funding' => ['string', new NotContainsEmail],
        ];
    }
}

I'm confused by the error, as the Laravel documentation clearly states that I can pass through an object, but Illuminate\Validation\ValidationRuleParser.php@217 clearly cannot handle objects.

Where have I gone wrong?

1
new NotContainsEmail or new NotContainsEmail() ??Davit
@Davit The laravel example docs provided have the new Uppercase syntax. See laravel.com/docs/5.6/validation#custom-validation-rulesuser7191988

1 Answers

1
votes

Using Extensions Another method of registering custom validation rules is using the extend method on the Validator facade. Let's use this method within a service provider to register a custom validation rule: https://laravel.com/docs/5.7/validation

In AppServiceProvider

public function boot()
{
    Validator::extend('NotContainsEmail', function ($attribute, $value, $parameters, $validator) {
        // code here
    });

    Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
        //return str_replace(...);
    });
}