1

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 Answer 1

2

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)
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.