Search code examples
phplaravellaravel-livewire

Correct email validations in PHP laravel Livewire


I want to validate emails correctly , the correct email must adhere to the following validation rules

(a) email must end with either .com , .gov , got , co , .uk , etc

(b)email must be unique

public $email = '';
    
        protected $rules = [
            'email' => 'required|email|min:3|unique:subscribers,email|regex:/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,3}$/',
        ];
    
        protected $messages = [
            'email.required' => 'The email field is required.',
            'email.email' => 'Please provide a valid email address.',
            'email.unique' => 'This email is already subscribed.',
            'email.regex' => 'The email must be a valid format (e.g., must include ".com").',
        ];
    
        public function updated($propertyName)
        {
            $this->validateOnly($propertyName);
        }
    
        public function submit()
        {
            $validated = $this->validate();
    
            // Save the email to the subscribers table
            Subscriber::create(['email' => $this->email]);
    
            // Send email
            Mail::to($this->email)->send(new SubscriptionMail($this->email));
    
            $this->reset();
            session()->flash('success', 'You have subscribed successfully!');
        }
   

the codes above does not work ,


Solution

  • have you tried validating what the emails end with:

    protected $allowedDomains = [
      '.com', '.gov', '.got', '.co', '.uk'
    ];
    
    protected $rules = [
      'email' => 'required|email|min:3|unique:subscribers,email|ends_with:'.implode(',',$this->allowedDomains),
    ];