I want to validate emails correctly as when user type in form field, the correct email must end with .com here is my code showing what i have been trying and it does not working
(the problem with the codes is it submit the form even if the email is not in the valid format , not ending with the specified domain )
(a) a complete form with email input field
@if(session()->has('success'))
<div class="alert alert-success" id="success-messagess">
{{ session('success') }}
</div>
@endif
<form wire:submit.prevent="submit" id="myForm">
@csrf
<div class="input-group">
<input wire:model.live.debounce.150ms="email" id="email" type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,3}" class="form-control @if($errors->has('email')) is-invalid @elseif($email && !$errors->has('email')) is-valid @endif" aria-describedby="emailHelp" placeholder="Enter email" name="email" autocomplete="off">
@if($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
<!-- Loading Spinner -->
<div wire:loading wire:target="submit" class="mt-2">
<div class="spinner-border text-primary" role="status">
<span class="sr-only">Loading...</span>
</div>
</div>
<div class="mt-2">
<span class="input-group-btn">
<button class="btn btn-danger" type="submit" id="subscribe" @if($errors->has('email') || !$email) disabled @endif wire:loading.attr="disabled">Subscribe</button>
</span>
</div>
</form>
(b) handling form submission
<?php
namespace AppLivewire;
use LivewireComponent;
use AppModelsSubscriber;
use AppMailSubscriptionMail;
use IlluminateSupportFacadesMail;
use IlluminateValidationRule;
class SubscriptionForm extends Component
{
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!');
}
public function render()
{
return view('livewire.subscription-form');
}
}