How to Validate Email and Password in Laravel

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

When building a web application, security is one of the primary concerns, especially when it comes to handling user credentials like email addresses and passwords. Laravel, a powerful PHP framework, makes the task of validation straightforward with its built-in functionality. In this tutorial, we will comprehensively cover the process of validating emails and passwords using Laravel.

Starting with Validation

Validation plays a crucial role in securing applications and maintaining data integrity. Laravel offers several ways to validate data; we’ll start with controller validation.

// In any controller method
$request->validate([
    'email' => 'required|email|unique:users,email',
    'password' => 'required|string|min:6',
]);

This simple block of code will ensure the email is both unique in the ‘users’ table and formatted correctly, and that the password meets the minimum length requirements.

Form Request Validation

For more complex scenarios, you might want to separate validation logic from your controllers. Laravel Form Request is a perfect tool for this.

php artisan make:request UserRegistrationRequest

Edit the created class to include validation rules:

public function rules()
{
    return [
        'email' => 'required|email|unique:users,email',
        'password' => 'required|min:6|confirmed',
    ];
}

Then, type-hint the request class in your controller method:

public function store(UserRegistrationRequest $request)
{
    // The incoming request is valid...

    // Retrieve the validated input...
    $validated = $request->validated();

    // Continue registration...
}

Custom Validation Rules

If predefined validation rules do not fit your needs, you can create custom rules.

php artisan make:rule ValidPassword

Then, define your logic in the created class:

public function passes($attribute, $value)
{
    return preg_match('/[A-Z]/', $value) && 
           preg_match('/[a-z]/', $value) && 
           preg_match('/[0-9]/', $value) && 
           strlen($value) >= 8;
}

public function message()
{
    return 'The :attribute must be at least 8 characters and include at least one uppercase letter, one lowercase letter, and one number.';
}

Now, use the custom rule like so:

'password' => ['required', new ValidPassword],

API Resources and Validation

In case you’re building an API, Laravel provides a very interesting feature called API Resources which can also incorporate validation:

public function toArray($request)
{
    return [
        'email' => 'required|email|unique:users,email',
        'password' => 'required|string|min:6',
    ];
}

This helps in transforming and formatting the API response data consistently.

Handling Validation Errors

The $errors variable is shared with all of your views by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group.

In blade templates, you can display error messages as follows:

@if ($errors->any())
  {{ $error }}
@endif

Advanced Validation Scenarios

For more advanced scenarios, you can use several other features like conditional validation, validation hooks, and even create complex validation scenarios by combining different validation rules.

'email' => [
    'required',
    Rule::unique('users')->where(function ($query) {
        return $query->where('account_id', 1);
    }),
],

'password' => [
    'required',
    function($attribute, $value, $fail) {
        if ($value !== 'my-secret-password') {
            $fail($attribute.' is invalid.');
        }
    },
]

Conclusion

In this tutorial, we covered how to validate emails and passwords in Laravel. From basic validation in controller methods to creating custom validation rules and advanced techniques, Laravel’s validation features are both robust and flexible, ensuring that user input can be effectively verified to keep your application secure and user-friendly.