A Comprehensive Guide to Laravel Validation

ArjunAmrutiya
3 min readSep 3, 2023

--

Introduction
Validation is a crucial aspect of web application development, ensuring that the data your application receives is accurate and secure. Laravel, a popular PHP framework, provides a robust and flexible validation system that makes it easy to validate user input. In this blog post, we will explore Laravel validation step by step, covering various validation methods with example code.

1. Basic Validation

Required Fields:
You can use the required validation rule to ensure that a field is not empty:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
'name' => 'required',
]);

String Length:
You can specify the minimum and maximum length of a string using min and max rules:

$validator = Validator::make($request->all(), [
'username' => 'min:3|max:20',
]);

Numeric Values:
To validate numeric input, use the numeric rule:

$validator = Validator::make($request->all(), [
'age' => 'numeric',
]);

2. Common Validation Rules

Email Validation:
Validate email addresses using the email rule:

$validator = Validator::make($request->all(), [
'email' => 'email',
]);

URL Validation:
Ensure URLs are valid using the url rule:

$validator = Validator::make($request->all(), [
'website' => 'url',
]);

Date and Date Format Validation:
Validate dates and date formats using the date rule:

$validator = Validator::make($request->all(), [
'dob' => 'date_format:Y-m-d',
]);

3. Custom Validation Rules

Creating Custom Validation Rules:
You can create custom validation rules by extending Laravel’s validator. For example, let’s create a custom rule to validate a Canadian postal code:

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class CanadianPostalCode implements Rule
{
public function passes($attribute, $value)
{
// Implement your validation logic here
}

public function message()
{
return 'The :attribute must be a valid Canadian postal code.';
}
}

Using Custom Rules:
Use your custom rule in validation:

use App\Rules\CanadianPostalCode;

$validator = Validator::make($request->all(), [
'postal_code' => ['required', new CanadianPostalCode],
]);

4. Conditional Validation

Required If:
Use the required_if rule to conditionally require a field based on another field's value:

$validator = Validator::make($request->all(), [
'credit_card' => 'required_if:payment_method,credit',
]);

Required Unless:
The required_unless rule makes a field required unless another field matches a certain value:

$validator = Validator::make($request->all(), [
'address' => 'required_unless:delivery_method,pickup',
]);

Required With:
Ensure a field is required when another field is present using the required_with rule:

$validator = Validator::make($request->all(), [
'emergency_contact' => 'required_with:has_medical_history',
]);

5. Validation Error Messages

Custom Error Messages:
Customize validation error messages by adding them to your validation rules:

$validator = Validator::make($request->all(), [
'email' => 'required|email',
], [
'email.required' => 'Please enter your email address.',
'email.email' => 'Invalid email format.',
]);

Displaying Validation Errors:
In your view, you can display validation errors using Laravel’s Blade templating engine:

@if ($errors->has('email'))
<div class="alert alert-danger">
{{ $errors->first('email') }}
</div>
@endif

6. Validation with Form Requests

Creating Form Requests:
Create dedicated Form Request classes to handle validation for specific routes or controllers:

php artisan make:request StoreBlogPostRequest

Using Form Requests in Controllers:
Use your Form Request class in your controller method:

public function store(StoreBlogPostRequest $request)
{
// Validated data is available here
}

7. Validating Arrays

You can validate arrays of data using the * wildcard:

$validator = Validator::make($request->all(), [
'tags.*' => 'alpha',
]);

8. Validation with AJAX

Laravel’s validation works seamlessly with AJAX requests. Send the data as JSON and handle validation errors in your JavaScript code.

Conclusion

Laravel provides a comprehensive validation system that allows you to ensure data integrity and security in your web applications. Whether you need to validate simple input fields or complex form submissions, Laravel’s validation capabilities have you covered. By following the examples and guidelines provided in this blog post, you can build robust and secure applications with confidence. Happy coding!

Go forth and get more out of your content. Go forth and conquer Medium! (and while you’re at it, follow me on Medium!)

Found this post useful? Kindly tap the 👏 button below! :)

🌟 Enjoy my blogging content? Support my work by buying me a virtual coffee on BuyMeACoffee! Your contributions help fuel insightful tech articles. Join hands in making coding more accessible and exciting for all. https://www.buymeacoffee.com/arjunamrutiya🚀

--

--

ArjunAmrutiya

👋 Hey there! I'm Arjun Amrutiya, a passionate web developer and blogger who loves all things PHP, Laravel and Vue.js. Welcome to my Medium account!