Laravel Validation: Mastering Custom Rules & Best Practices

One of the critical parts of safeguarding a website or application is user validation. To address that, Laravel, one of the best PHP frameworks, offers a robust validation system.

The built-in rules encompass common validation requirements like verifying presence, format, and uniqueness of data. But the Laravel experts can also extend the capabilities by crafting custom rules bespoke to the application.

In this blog, I’ll tell you all about creating and applying validation rules in Laravel. So let’s begin.

What are Validation Rules in Laravel?

Validation rules are predefined or custom sets of conditions. It ensures the submitted data adheres to specific criteria before it’s processed by your Laravel application. These rules act as a safeguard against erroneous or malicious user input. They protect your application’s data integrity and enhance its overall security.

Laravel offers a comprehensive set of built-in validation rules covering common scenarios like:

  • Required: Ensures the field is not empty or null.
  • Email: Validates the format of an email address.
  • Numeric: Verifies if the field contains only numeric characters.
  • Unique: Checks if the field’s value already exists in a specific database table.

Laravel also lets you create custom validation rules tailored to your application’s unique requirements. This flexibility lets you address particular validation requirements beyond the built-in options.

So why do the Laravel development services stress on applying the validation rules in the applications? Let’s see.

Why Create and Apply Validation Rules in Laravel?

Validation rules are a cornerstone of Laravel security practices. They help you maintain data integrity, safeguard your application, and provide a positive user experience. Let’s take a look at a few reasons to create and apply validation rules in Laravel:

Enhanced Data Integrity

Validation rules act as a crucial line of defense against inaccurate or invalid data entering your application. They define specific criteria for each data field. That way, you can ensure that only pertinent and well-formatted information is processed. It prevents inconsistencies and errors within your application’s logic and database.

This fosters a reliable foundation for building upon and allows you to make data-driven decisions.

Robust Security

Unvalidated user input can pose significant security vulnerabilities. Malicious actors might exploit these vulnerabilities to inject malicious code or manipulate data. That compromises the integrity and security of your application. Implementing validation rules acts as a safeguard against such threats.

By enforcing specific criteria on user input, you significantly minimize the risk of security breaches. That protects sensitive information and maintains the overall security posture of your application.

Streamlined User Experience

Validation rules play a crucial role in providing a positive and user-friendly experience. When users encounter errors due to invalid input, they can get confused. And unclear or unhelpful error messages only lead to further frustration.

By implementing informative validation messages alongside the rules, you can guide users towards correcting their mistakes effectively. That saves users time and effort and fosters a sense of trust and transparency within your application.

Improved Code Maintainability

Validation rules contribute to cleaner and more organized code. Encapsulate validation logic within dedicated rules or form request classes. That helps separate it from the core application logic. It enhances code readability and maintainability. And the process of modifying or adding new validation requirements in the future is simplified.

Prioritize data integrity, safeguarding security, and fostering a positive user experience. So you can build robust and reliable web applications that stand the test of time.

Want to secure your Laravel website with robust validation?

How to Create Validation Rules in Laravel?

When it comes to validation in Laravel websites and applications, the Laravel experts go about two different approaches. Built-in and Customized. Here’s a breakdown of both methods.

Through Built-in Validation Rules

Laravel offers a comprehensive set of pre-defined validation rules that cover common scenarios. You can leverage these rules within your Controllers and Form Request Classes.

  • Controllers: Define the rules within the rules method of your controller. It returns an associative array where the key is the field name and the value is the validation rule(s) applied.
public function store(Request $request)
{
  $rules = [
    'name' => 'required|string|max:255',
    'email' => 'required|email|unique:users,email',
  ];

  // ... rest of your controller logic
}
  • Form Request Classes: Create a dedicated form request class extending the Illuminate\Foundation\Http\FormRequest class. Define the rules method similar to controllers, and use the authorize method for additional authorization logic.
class StoreUserRequest extends FormRequest
{
  public function rules()
  {
    return [
      'name' => 'required|string|max:255',
      'email' => 'required|email|unique:users,email',
    ];
  }

  public function authorize()
  {
    return true; // Replace with your authorization logic
  }
}

Craft Custom Validation Rules

Let’s say your scenarios go beyond the scope of built-in rules. In that case, custom validation rules. That involves:

  • Creating a Rule Class: Extend the Illuminate\Validation\Rule class and define two methods:
    • passes: This method receives the value to be validated, the attribute name, and a callback (optional). It should return true if the validation passes, false otherwise.
    • message: This method returns the error message to be displayed if validation fails.
class IsUpperCaseRule extends Rule

{

  public function passes($attribute, $value)

  {

    return mb_strtoupper($value) === $value;

  }

  public function message()

  {

    return 'The :attribute field must be in uppercase.';

  }

}
  • Using the Custom Rule: Once created, you can use your custom rule like any other built-in rule in your rules method:
$rules = [

  'title' => 'required|string|max:255',

  'content' => 'required|string',

  'custom_field' => [new IsUpperCaseRule],

];

Make sure you replace the placeholders “name” and “email” with your actual field names. And, tailor the rules and messages based on your requirements.

How to Apply Validation Rules in Laravel?

Applying validation rules in Laravel websites or applications isn’t as simple as you may think. You need to integrate them into your application’s workflow. There are two methods to go about it.

Using Validation with Requests

This approach of applying validation rules in Laravel leverages the validate method provided by the Illuminate\Http\Request object:

public function store(Request $request)

{

  $rules = [

    'name' => 'required|string|max:255',

    'email' => 'required|email|unique:users,email',

  ];

  $request->validate($rules);

  // ... rest of your controller logic, where the data is guaranteed to be valid

}

In this approach, the validate method takes the validation rules as an argument. It performs the validation against the request data. It also throws a ValidationException if the validation fails. That automatically redirects the user back to the previous URL.

Using Form Request Classes

This method of applying validation rules in Laravel involves creating a dedicated form request class:

  • Create a Form Request Class: Extend the Illuminate\Foundation\Http\FormRequest class and define the following methods:
    • rules: Define the validation rules within this method, similar to the controller approach.
    • authorize: Implement any authorization logic specific to the request (optional).
class StoreUserRequest extends FormRequest

{

  public function rules()

  {

    return [

      'name' => 'required|string|max:255',

      'email' => 'required|email|unique:users,email',

    ];

  }

  public function authorize()

  {

    return true; // Replace with your authorization logic

  }

}
  • Use the Form Request Class in your Controller
public function store(StoreUserRequest $request)

{

  // Access validated data directly from the request object

  $name = $request->name;

  $email = $request->email;

  // ... rest of your controller logic, where the data is guaranteed to be valid

}

Here, the StoreUserRequest class handles the validation, and the controller receives the validated data directly through the request object. This approach separates validation logic from the controller for cleaner code organization.

Although both methods are effective, you need to choose the one that best aligns with the structure of your site or app. If you need help with that, I suggest you consult with our Laravel development company.

What are the Different Types of Validation Rules in Laravel?

As mentioned earlier, Laravel offers a comprehensive set of built-in validation rules for various data types and validation requirements. Here’s an overview of the different categories of validation rules available:

Basic Validation

  • required: Ensures the field is not empty or null.
  • nullable: Allows the field to be empty or null.
  • present: The field must be present in the request, but it can be empty.
  • confirmed: Verifies if the field value matches the confirmation field value (commonly used for passwords).

Data Type Validation

  • string: Validates if the field contains only text characters.
  • integer: Validates if the field contains only integer values.
  • numeric: Validates if the field contains only numeric characters (including decimals).
  • array: Verifies if the field is an array.
  • boolean: Ensures the field’s value is either true or false.

Format Validation

  • email: Validates the format of an email address.
  • date: Verifies if the field contains a valid date format.
  • date_format: Ensures the field’s date adheres to a specific format (e.g., “Y-m-d”).
  • ip: Validates if the field contains a valid IP address.
  • url: Checks if the field contains a valid URL.

Size and Length Validation

  • min: Sets a minimum length requirement for the field’s value (e.g., min:8 for passwords).
  • max: Defines a maximum length restriction for the field’s value.
  • between: Validates if the field’s value falls within a specified range (e.g., between:5,10 for characters).
  • size: Restricts the size of uploaded files (in kilobytes, megabytes, etc.).

Comparison Validation

  • same: Compares the field’s value with another field’s value (e.g., same: password for password confirmation).
  • different: Ensures the field’s value is different from another field’s value.
  • in: Verifies if the field’s value is present within a specified list of values (e.g., in:admin,editor,user).
  • not_in: Checks if the field’s value is not present within a specified list of values.

Database Validation

  • unique: Guarantees the field’s value is unique within a specific database table and column.
  • exists: Verifies if the field’s value exists in a specified database table and column.

Other Validation Rules

  • alpha: Ensures the field contains only alphabetic characters (a-z and A-Z).
  • alpha_dash: Allows alphabetic characters, underscores, and hyphens.
  • alpha_num: Permits alphabetic characters and numbers.
  • regex: Validates the field’s value against a regular expression.
  • mimes: Restricts the allowed MIME types for uploaded files (e.g., mimes:image,pdf,docx).

There are several other validation rules for which you may need to consult the official Laravel documentation. It gives a better overview of these rules and their usage. Or you can consult dedicated Laravel development experts.

FAQs on Creating and Applying Validation Rules in Laravel

Can I customize the error messages for validation rules in Laravel?
Yes, you can customize the error messages for validation rules in Laravel. You can do this by passing an array of custom messages as the third parameter to the validate method. You can also use the messages method on the Validator facade to set custom error messages for specific fields.
What are some common validation rules in Laravel?
Some common validation rules in Laravel include required for making a field mandatory, email for validating email addresses, numeric for accepting only numbers, and min and max for specifying minimum and maximum lengths for a field.
How can I test my validation rules in Laravel?
Laravel provides a built-in Validator class for testing your validation rules. You can use the passes method to check if the input data passes all the rules, and the fails method to check if any of the rules fail. You can also use the Validator facade in your unit tests to test validation rules.

To Conclude

Validation rules in Laravel are a set of predefined protocols that validate user input data before it’s processed by the application. These rules ensure that the data is in the correct format and meets certain requirements.

To create validation rules in Laravel, you can use the built-in Validator class or create a custom validation rule. And custom validation rules can be created by extending the Validator class and adding your own validation logic.

To apply validation rules in Laravel, you can use the validate method in your controller. This method takes in the HTTP request and an array of validation rules.

If you need help with the validation rules on your Laravel application, consult with our Laravel specialists today!

Want to take your Laravel Application to the next level?

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment