I am using laravel 8. I need to validate 3 fields to make 1 phone number. The flow is to combine the 3 fields and then save to database. Validation is triggered when one of the fields is not the correct format ( typed in char, more than 4 digits, etc ). The validation error message should only be for the first field. Meaning I need to delete the 2nd and 3rd fields' error message and just update/create the error message on the first field.
Validation itself is done but I cannot delete the error message when returning to the frontend. If possible, I dont want to update the front end code for this since this is a laravel logic.
This is my version of the failedValidation method:
protected function failedValidation(Validator $validator)
{
$errorMessages = $validator->errors();
$messages = $errorMessages->getMessages();
if ($errorMessages->has('phNo_1') || $errorMessages->has('phNo_2') || $errorMessages->has('phNo_3')) {
$errorMessages->add('phNo_1', $errorMessages->first('phNo_1'));
unset($messages['phNo_2']);
unset($messages['phNo_3']);
}
parent::failedValidation($validator);
}
The code is based in this SO answer. When I log the $messages, I can see that the phNo_2 and phNo_3's message is already deleted but I am unable to assign it back to $validator.
I am aware of the forget method of $validator->errors() but the method is for laravel 10.
Additional Code:
ValidPhoneNumber.php
public function __construct($input)
{
$this->input = $input;
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$ph_01 = $this->input['phNo_1'];
$ph_02 = $this->input['phNo_2'];
$ph_03 = $this->input['phNo_3'];
// Check if all fields are required or null
if (empty($ph_01) && empty($ph_02) && empty($ph_03)) {
return true;
}
// Check if all fields are integers and have max 4 digits
if (is_numeric($ph_01) && is_numeric($ph_02) && is_numeric($ph_03)) {
if (strlen($ph_01) <= 4 && strlen($ph_02) <= 4 && strlen($ph_03) <= 4) {
return true;
}
}
return false;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The validation error message.';
}
FormRequest:
public function rules()
{
return [
...
'phNo_1' => ['nullable', 'required_with:phNo_2,phNo_3', new ValidPhoneNumber($this->input())],
'phNo_2' => ['nullable', 'required_with:phNo_1,phNo_3', new ValidPhoneNumber($this->input())],
'phNo_3' => ['nullable', 'required_with:phNo_1,phNo_2', new ValidPhoneNumber($this->input())],
...
];
}