Laravel Form Validation
Client-Side and Server-Side Validation
- Client-Side Validation: In JavaScript, hackers can bypass it.
- Server-Side Validation: Hackers cannot bypass it, it is secure. Used in Laravel.
CSRF Token
- First, pass the CSRF token in the form.
- Important for server and client-side validation.
Using Form Validation
- Add User Function in Controller:
- Use the
Request
class.
- Use the
validate
method for field validation.
- Validation Rules:
required
: Field is mandatory.
email
: Must be a valid email address.
numeric
: Value must be numeric.
Form HTML
- Include the CSRF token.
- Fields: User Name, Email, AGE, City (Select Box)
- Submit Button: Submit the form.
Using Validation in Controller
public function addUser(Request $request) {
$request->validate([
'user_name' => 'required',
'user_email' => 'required|email',
'user_age' => 'required|numeric|min:18|max:65'
]);
// Validation for maximum and minimum age
}
Logging Errors
- Print Errors: Use
@errors->all()
.
- Error Messages in Form:
@error('field_name') <div>{{ $message }}</div>@enderror
Custom Validation Messages
- Define Custom Rules in the Third Parameter:
$request->validate([
'user_name' => 'required',
'user_email' => 'required|email',
'user_password' => 'required|min:6|alpha_num'
], [
'user_name.required' => 'User name is required',
'user_email.email' => 'Your email is not correct',
// Other custom messages
]);
Available Validation Rules
File for Customization
- Edit the
lang/en/validation.php
file to customize validation messages.
Useful Validation Rules for Reference
- With Range:
min:XX
, max:XX
, between:XX,YY
, confirmed
(for password confirmation)
- Error Message Customization:
'attribute' => 'use a good name'
Tips
- CSRF Token: Ensure to use the CSRF token in all forms.
- Custom Messages in Validator: Personalize the errors.
- Data Protection: Ensure validation of all important data.
Conclusion
- Key differences between client and server-side validation.
- Important validation rules in Laravel.
- How to create custom error messages.
- Use of all Laravel validation rules available in the documentation.