1

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?

2
  • Can you please share the error message? Commented Oct 28, 2018 at 22:04
  • It might be that you're not explicitly returning true from function passes(). The default return value if you don't return something is null which might be evaluating to false. Commented Oct 28, 2018 at 22:09

2 Answers 2

2

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';
    }
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.