Cosmin
Cosmin

Reputation: 954

Change validation message for a custom validation rule in Laravel

I'm trying to write a custom validation rule in Laravel to ensure that every email in a comma separated list is not on a suppression list. I already have a different rule that verifies if every email in the comma separated list is a valid email, so I don't check that here.

The code above works fine, but I have two questions:

  1. Can I do this better?
  2. How can I modify the error message to include the email address that's not correct? I want it to say something like "The email address [email protected] is on the suppression list and will not be used for sending".
public function passes($attribute, $value)
{
    $emails = explode(',', $value);

    foreach ($emails as $email) {
        $onSuppressionList = $this->suppressionListManager->find($email);
        
        if ($onSuppressionList) {
            return false;
        }               
    }

    return true;
}

public function message()
{
    return 'The validation error message.';
}

Upvotes: 0

Views: 191

Answers (1)

John Lobo
John Lobo

Reputation: 15319

Declare property called $suppressionList like below

  private $suppressionList=[];

then change passes as

public function passes($attribute, $value)
    {
        $emails = explode(',', $value);


        foreach ($emails as $email) {
            $onSuppressionList = $this->suppressionListManager->find($email);

            if ($onSuppressionList) {

                $this->suppressionList[]=$email;
            }
        }

        if(count($this->suppressionList)){

            return false;
        }

        return true;
    }

then in custom message

 public function message()
    {
        $emails=implode(",",$this->onSuppressionList);
        return 'The email address '.$emails.'is on the suppression list and will not be used for sending';
    }

For appending emails in message you can use sprintf too

Upvotes: 1

Related Questions