0

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.';
}

4
  • public function passes($attribute, $value) { $emails = explode(',', $value); $onSuppressionList = $this->suppressionListManager->whereIn('email',$emails)->exists(); if ($onSuppressionList) { return false; } } return true; } Commented Jun 14, 2021 at 12:20
  • what about this ?.not sure i am guessing you can check wherein emails Commented Jun 14, 2021 at 12:22
  • SuppressionListManager is an utility class. It's not an Eloquent model. That part is fine, no need to change it. Commented Jun 14, 2021 at 12:28
  • i posted answer.let me know if any issues Commented Jun 14, 2021 at 12:30

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

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.