Loading image

Blogs / Programming

In-Depth Guide to Laravel Validation Rules for Special Fields

In-Depth Guide to Laravel Validation Rules for Special Fields

  • showkat ali
  • 0 Comments
  • 54 View

Laravel provides a powerful and flexible validation system that lets developers ensure data accuracy, completeness, and security with ease. This guide focuses on core validation rules, field-specific validations, and regex-based customizations for various input types, covering usernames, emails, passwords, phone numbers, dates, and more. We'll also include conditional and specialized rules for precise validation control.


1. Basic Validation Rules for Common Fields

These core validation rules set the foundation for input requirements, covering presence, nullability, and data type.

  • required: Field must be present and non-empty.
  • nullable: Allows a field to be empty or null.
  • present: Ensures the field is in the request, even if it’s empty.
  • filled: Field must have a value if present.
  • sometimes: Applies validation only if the field is included.

Example:

'username' => 'required|string|max:50',
'age' => 'nullable|integer|min:0',

 


2. String and Length-Specific Rules

String fields often require specific lengths or alphabetic/alpha-numeric characters.

  • string: Checks if the value is a string.
  • min:<number>: Minimum character length.
  • max:<number>: Maximum character length.
  • between:<min>,<max>: Value length within a range.
  • size:<number>: Exact length.

Example:

'username' => 'required|string|between:5,15|alpha_num|unique:users,username',

 


3. Regex-Based Custom Validation for Special Fields

Regex enables enforcing patterns like alphanumeric usernames or complex password formats.

  • regex:<pattern>: Validates with a custom regular expression.

Common Patterns:

  • Username: Only alphanumeric, 5-15 characters.
  • Password: Minimum 8 characters, at least one letter and one number.
  • Phone Number: Allows a Pakistani format (e.g., +92 or 0 followed by 10 digits).
  • Address: Allows letters, numbers, and symbols such as spaces, commas, periods, or hyphens.

Example:

'username' => 'required|string|between:5,15|alpha_num|unique:users,username',
'password' => 'required|string|min:8|confirmed|regex:/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/',
'phone' => 'nullable|numeric|digits_between:10,15|regex:/^(\+92|0)?[0-9]{10}$/',
'address' => 'nullable|string|max:255|regex:/^[\w\s,.-]+$/',

 


4. Date-Specific Validation Rules

Date rules can enforce valid date formats, ranges, and conditions for relative comparisons.

  • date: Checks if the field is a valid date.
  • before:<date>: Date must be before a specific date.
  • after:<date>: Date must be after a specific date.
  • date_equals:<date>: Exact date match.
  • date_format:<format>: Ensures the date follows a specified format.

Example:

'date_of_birth' => 'required|date|before:today',

 


 

5. Conditional Validation Rules for Special Scenarios

Conditional validation is helpful when some fields are required only if certain conditions are met.

  • required_if:<other_field>,<value>: Field is required if another field has a specific value.
  • required_with:<fields>: Field is required if any of the specified fields are present.
  • required_without:<fields>: Field is required if any of the specified fields are absent.

Example:

'state' => 'required_if:country,US',
'address' => 'required_with:city,zipcode',
'status' => 'required_if:role,admin|in:active,inactive',

 

 


6. Numeric and Range Rules

Numeric validation can enforce integer-only values, minimum and maximum ranges, and decimal precision.

  • integer: Ensures an integer value.
  • numeric: Checks if the field is a number.
  • digits:<number>: Requires an exact number of digits.
  • digits_between:<min>,<max>: Ensures a specific digit range.
  • decimal:<places>: Restricts decimal precision.
  • between:<min>,<max>: Specifies a numeric range.

Example:

'salary' => 'nullable|numeric|between:1000,50000|decimal:2',

 

 


7. Specialized Rules for File and Image Uploads

When handling file uploads, Laravel can validate file types, sizes, and image dimensions.

  • file: Ensures the field is a file.
  • image: Restricts the field to image files.
  • mimes:<types>: Limits file types (e.g., jpeg, png).
  • max:<kilobytes>: Limits file size.
  • dimensions: Restricts image dimensions.

Example:

'profile_picture' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',

 

 


8. JSON and Array-Specific Rules

JSON and array validation rules enforce correct structure and ensure that array values are unique or exist in a database.

  • json: Ensures the field is valid JSON.
  • array: Ensures the field is an array.
  • distinct: Requires unique values in an array.
  • exists:<table>,<column>: Ensures array elements exist in a database table.

Example:

 

'json_field' => 'nullable|json',
'roles' => 'array|distinct',
'roles.*' => 'exists:roles,id',

 

 


Example of a Comprehensive Validation Rule Set

Below is a sample FormRequest validation that brings together these rules for a comprehensive validation example, covering usernames, emails, passwords, phone numbers, dates, file uploads, and more.

 

public function rules()
{
    return [
        'username' => 'required|string|between:5,15|alpha_num|unique:users,username',
        'email' => 'required|email|unique:users,email',
        'password' => 'required|string|min:8|confirmed|regex:/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/',
        'phone' => 'nullable|numeric|digits_between:10,15|regex:/^(\+92|0)?[0-9]{10}$/',
        'date_of_birth' => 'required|date|before:today',
        'profile_picture' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        'address' => 'required_with:city,zipcode|string|max:255|regex:/^[\w\s,.-]+$/',
        'status' => 'required_if:role,admin|in:active,inactive',
        'salary' => 'nullable|numeric|between:1000,50000|decimal:2',
        'json_field' => 'nullable|json',
        'roles' => 'array|distinct',
        'roles.*' => 'exists:roles,id',
    ];
}

 

 


Conclusion

With Laravel’s extensive validation options, you can tailor your application’s validation to meet almost any requirement. From simple presence checks to complex conditional and regex-based validations, Laravel makes it easy to ensure that your data is clean and compliant with business rules. Following these examples will give you a strong foundation in crafting validations for any type of data, whether it’s numeric, text, file uploads, or arrays.

 

 

 

  • Programming
showkat ali Author

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur based in Pakistan. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance

0 Comments

Post Comment

Recent Blogs

Recent posts form our Blog

How to install and Use CKEditor  in Laravel 10

How to install and Use CKEditor in Laravel 10

showkat ali
/
Programming

Read More
How to Make Your Website Faster: Speed and SEO Tips

How to Make Your Website Faster: Speed and SEO Tips

showkat ali
/
Technology

Read More
Figurative Language (Simile and Metaphor)

Figurative Language (Simile and Metaphor)

Nasir Hussain
/
English

Read More
A Step-by-Step Guide: How to Integrate CoinGate with Laravel 10

A Step-by-Step Guide: How to Integrate CoinGate with Laravel 10

showkat ali
/
Programming

Read More
How to Create a Dynamic Select2 Dropdown with Laravel and AJAX

How to Create a Dynamic Select2 Dropdown with Laravel and AJAX

showkat ali
/
Programming

Read More
Top 10+ Best Web Frameworks to Learn for a Successful Web Development Career

Top 10+ Best Web Frameworks to Learn for a Successful Web Development Career

showkat ali
/
Programming

Read More