shekwo
shekwo

Reputation: 1447

Error implementing Custom Validation in Laravel

I am trying to add an extra validation rule that checks to ensure that a username is a word. I created a new rule (SingleWord) like so:

public function passes($attribute, $value)
    { 
        $dd =  strpos(trim($value), ' ');
        if($dd !== false){
            return false;
        }
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Username must be one word';
    }

I now added this rule to the validator like so:

 $validator =  Validator::make($data, [
            'name' => 'required|string|max:255|unique:merchants',
            'email' => 'required|string|email|max:255|unique:merchants',
            'password' => 'required|string|min:6',
            'username' => 'required|string|unique:merchants',
            'username' => [new SingleWord]
        ],[
            'name.required' => "Company name is required",
        ]);
        return $validator;

But the validator returns the error message even when I enter one word. Please what might be wrong here?

Upvotes: 1

Views: 38

Answers (2)

Elisha Senoo
Elisha Senoo

Reputation: 3594

You left out the affirmative case. Try this:

public function passes($attribute, $value)
    { 
        $dd =  strpos(trim($value), ' ');
        if($dd !== false){
            return false;
        }
        return true; 
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Username must be one word';
    }

Upvotes: 2

nakov
nakov

Reputation: 14268

Without knowing your error message, I will suggest couple of changes, first in your validation you can change your passes method to this:

public function passes($attribute, $value)
{ 
    return !strpos(trim($value), ' ');
}

and then your validation, you can use only one key like this:

'username' => ['required', 'string', 'unique:merchants' , new SingleWord]

Upvotes: 1

Related Questions