Laravel custom validaion rules with custom message set.
2 min readAug 28, 2022
Applying in student login page:
There are some way to do this based on requirements —
- Login success when only status is active
$this->validate($request, [
'email' => 'exists:students,email,status,active',
], [
'email.exists' => 'Your account is not activated yet. Please verify email or contact with authority.'
]);
2. When need more to check by database query
Firstly check basic email password validation, then set rules with query, message set, apply validation and return validation message if validation fails.
/**
* General email validation with exists check
*/
$this->validate($request, [
'email' => 'required|email|exists:students,email',
'password' => 'required',
]);
/**
* Custom validation rules, message return and validate
*/
$rules = [
'email' => [
Rule::exists('students', 'email')->where(function ($query) {
return $query->where('status', '!=', 'un_verified')->where('email_verified_at', '!=', '');
}),
],
];
$messages = ['email.exists' => 'Your account is not activated yet. Please verify email or contact with authority.'];
$email = Validator::make($request->all(), $rules, $messages);
if ($email->fails()) {
return redirect()->route('student.student_login')->withErrors($email)->withInput();
}
— Shah Md. Iktakhirul Islam, Software Engineer.
Contact Number: +8801683201359
Email: iktakhairul@gmail.com
GitHub Profile: https://github.com/iktakhairul