0
votes

I have the following working validation rule which checks to make sure each recipient,cc,bcc list of emails contain valid email addresses:

  return [
            'recipients.*' => 'email',
            'cc.*' => 'email',
            'bcc.*' => 'email',
        ];

I need to also be able to allow the string ###EMAIL### as well as email validation for each of these rules and struggling to create a custom validation rule in Laravel 5.8 (it can't be upgraded at this time).

Any idea how to go about this? If it were a higher version of Laravel I was thinking something like (not tested) to give you an idea of what I'm trying to do:

return [
    'recipients.*' => 'exclude_if:recipients.*,###EMAIL###|email',
    'cc.*' => 'exclude_if:recipients.*,###EMAIL###|email',
    'bcc.*' => 'exclude_if:recipients.*,###EMAIL###|email',
];
1

1 Answers

1
votes

In 5.8 you can create Custom Rule Object Let's see how we can actually make it work.

  1. Create your rule with php artisan make:rule EmailRule
  2. Make it to look like this
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class EmailRule implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if ($value === '###EMAIL###' or filter_var($value, FILTER_VALIDATE_EMAIL)) {
            return true;
        }
        return false;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'The :attribute must be valid email or ###EMAIL###.';
    }
}
  1. Include in your rules so it looks like
return [
    'recipients.*' => [new EmailRule()],
    'cc.*' => [new EmailRule()],
    'bcc.*' => [new EmailRule()],
];
  1. Write a test (optional)