PHPackages                             webman/validation - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. webman/validation

ActiveLibrary

webman/validation
=================

Webman plugin webman/validation

v2.2.1(2mo ago)11.3k—6.9%1MITPHP

Since Feb 21Pushed 2mo agoCompare

[ Source](https://github.com/webman-php/validation)[ Packagist](https://packagist.org/packages/webman/validation)[ RSS](/packages/webman-validation/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (5)Versions (3)Used By (1)

English | [中文](./README.zh-CN.md)

Webman Validation
=================

[](#webman-validation)

Webman's validation component, based on `illuminate/validation`, provides manual validation, annotation-based validation, parameter-level validation, and reusable rule sets.

Installation
------------

[](#installation)

```
composer require webman/validation
```

Basic Concepts
--------------

[](#basic-concepts)

- **Rule Set Reuse**: Define reusable `rules`, `messages`, `attributes`, and `scenes` by extending `support\validation\Validator`, which can be reused in manual and annotation validation.
- **Annotation (Attribute) Validation - Method-Level**: Use the PHP 8 attribute `#[Validate]` to bind validation to controller methods.
- **Annotation (Attribute) Validation - Parameter-Level**: Use the PHP 8 attribute `#[Param]` to bind validation to controller method parameters.
- **Exception Handling**: Throws `support\validation\ValidationException` on validation failure; the exception class is configurable via config.
- **Database Validation**: If database validation is involved, you need to install `composer require webman/database`.

Manual Validation
-----------------

[](#manual-validation)

### Basic Usage

[](#basic-usage)

```
use support\validation\Validator;

$data = ['email' => 'user@example.com'];

Validator::make($data, [
    'email' => 'required|email',
])->validate();
```

> **Note**
> `validate()` will throw `support\validation\ValidationException` if validation fails. If you prefer not to throw exceptions, use `fails()` as shown below.

### Custom Messages and Attributes

[](#custom-messages-and-attributes)

```
use support\validation\Validator;

$data = ['contact' => 'user@example.com'];

Validator::make(
    $data,
    ['contact' => 'required|email'],
    ['contact.email' => 'Invalid email format'],
    ['contact' => 'Email']
)->validate();
```

### Validate Without Exception (Get Error Messages)

[](#validate-without-exception-get-error-messages)

If you don't want exceptions, use `fails()` and read errors from the `MessageBag`:

```
use support\validation\Validator;

$data = ['email' => 'bad-email'];

$validator = Validator::make($data, [
    'email' => 'required|email',
]);

if ($validator->fails()) {
    $firstError = $validator->errors()->first();   // string
    $allErrors = $validator->errors()->all();      // array
    $errorsByField = $validator->errors()->toArray(); // array
    // handle errors...
}
```

Rule Set Reuse (Custom Validator)
---------------------------------

[](#rule-set-reuse-custom-validator)

```
namespace app\validation;

use support\validation\Validator;

class UserValidator extends Validator
{
    protected array $rules = [
        'id' => 'required|integer|min:1',
        'name' => 'required|string|min:2|max:20',
        'email' => 'required|email',
    ];

    protected array $messages = [
        'name.required' => 'Name is required',
        'email.required' => 'Email is required',
        'email.email' => 'Invalid email format',
    ];

    protected array $attributes = [
        'name' => 'Name',
        'email' => 'Email',
    ];
}
```

### Manual Validation Reuse

[](#manual-validation-reuse)

```
use app\validation\UserValidator;

UserValidator::make($data)->validate();
```

### Use Scenes (Optional)

[](#use-scenes-optional)

Scenes are optional. They are only used when you call `withScene(...)` to validate a subset of fields.

```
namespace app\validation;

use support\validation\Validator;

class UserValidator extends Validator
{
    protected array $rules = [
        'id' => 'required|integer|min:1',
        'name' => 'required|string|min:2|max:20',
        'email' => 'required|email',
    ];

    protected array $scenes = [
        'create' => ['name', 'email'],
        'update' => ['id', 'name', 'email'],
    ];
}
```

```
use app\validation\UserValidator;

// No scene specified -> validate all rules
UserValidator::make($data)->validate();

// Specify scene -> validate only fields in that scene
UserValidator::make($data)->withScene('create')->validate();
```

Annotation Validation (Method-Level)
------------------------------------

[](#annotation-validation-method-level)

### Direct Rules

[](#direct-rules)

```
use support\Request;
use support\validation\annotation\Validate;

class AuthController
{
    #[Validate(
        rules: [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ],
        messages: [
            'email.required' => 'Email is required',
            'password.required' => 'Password is required',
        ],
        attributes: [
            'email' => 'Email',
            'password' => 'Password',
        ]
    )]
    public function login(Request $request)
    {
        return json(['code' => 0, 'msg' => 'ok']);
    }
}
```

### Reusing Rule Sets

[](#reusing-rule-sets)

```
use app\validation\UserValidator;
use support\Request;
use support\validation\annotation\Validate;

class UserController
{
    #[Validate(validator: UserValidator::class, scene: 'create')]
    public function create(Request $request)
    {
        return json(['code' => 0, 'msg' => 'ok']);
    }
}
```

### Multiple Validation Overlays

[](#multiple-validation-overlays)

```
use support\validation\annotation\Validate;

class UserController
{
    #[Validate(rules: ['email' => 'required|email'])]
    #[Validate(rules: ['token' => 'required|string'])]
    public function send()
    {
        return json(['code' => 0, 'msg' => 'ok']);
    }
}
```

### Validation Data Source

[](#validation-data-source)

```
use support\validation\annotation\Validate;

class UserController
{
    #[Validate(
        rules: ['email' => 'required|email'],
        in: ['query', 'body', 'path']
    )]
    public function send()
    {
        return json(['code' => 0, 'msg' => 'ok']);
    }
}
```

Use `in` to specify where validation data comes from:

- **query** – HTTP query parameters from `$request->get()`
- **body** – HTTP body from `$request->post()`
- **path** – Path/route parameters from `$request->route->param()`

`in` can be a string or array; when it's an array, values are merged in order and later sources override earlier ones. When `in` is omitted, it defaults to the equivalent of `['query', 'body', 'path']`.

Parameter-Level Validation (Param)
----------------------------------

[](#parameter-level-validation-param)

### Basic Usage

[](#basic-usage-1)

```
use support\validation\annotation\Param;

class MailController
{
    public function send(
        #[Param(rules: 'required|email')] string $from,
        #[Param(rules: 'required|email')] string $to,
        #[Param(rules: 'required|string|min:1|max:500')] string $content
    ) {
        return json(['code' => 0, 'msg' => 'ok']);
    }
}
```

### Validation Data Source

[](#validation-data-source-1)

Parameter-level validation also supports the `in` parameter to specify data source:

```
use support\validation\annotation\Param;

class MailController
{
    public function send(
        #[Param(rules: 'required|email', in: ['body'])] string $from
    ) {
        return json(['code' => 0, 'msg' => 'ok']);
    }
}
```

### Rules Support String or Array

[](#rules-support-string-or-array)

```
use support\validation\annotation\Param;

class MailController
{
    public function send(
        #[Param(rules: ['required', 'email'])] string $from
    ) {
        return json(['code' => 0, 'msg' => 'ok']);
    }
}
```

### Custom Messages / Attribute

[](#custom-messages--attribute)

```
use support\validation\annotation\Param;

class UserController
{
    public function updateEmail(
        #[Param(
            rules: 'required|email',
            messages: ['email.email' => 'Invalid email format'],
            attribute: 'Email'
        )]
        string $email
    ) {
        return json(['code' => 0, 'msg' => 'ok']);
    }
}
```

### Reusing Rule Constants

[](#reusing-rule-constants)

```
final class ParamRules
{
    public const EMAIL = ['required', 'email'];
}

class UserController
{
    public function send(
        #[Param(rules: ParamRules::EMAIL)] string $email
    ) {
        return json(['code' => 0, 'msg' => 'ok']);
    }
}
```

Method-Level + Parameter-Level Mixing
-------------------------------------

[](#method-level--parameter-level-mixing)

```
use support\Request;
use support\validation\annotation\Param;
use support\validation\annotation\Validate;

class UserController
{
    #[Validate(rules: ['token' => 'required|string'])]
    public function send(
        Request $request,
        #[Param(rules: 'required|email')] string $from,
        #[Param(rules: 'required|integer')] int $id
    ) {
        return json(['code' => 0, 'msg' => 'ok']);
    }
}
```

Automatic Rule Inference (Signature-Based)
------------------------------------------

[](#automatic-rule-inference-signature-based)

When a method uses `#[Validate]`, or any parameter on that method uses `#[Param]`, this package will **infer and auto-complete basic validation rules from the PHP method signature**, then merge them with your existing rules and run validation.

### Examples: `#[Validate]` Equivalent Expansion

[](#examples-validate-equivalent-expansion)

1. Enable `#[Validate]` without writing rules:

```
use support\validation\annotation\Validate;

class DemoController
{
    #[Validate]
    public function create(string $content, int $uid)
    {
    }
}
```

Equivalent to:

```
use support\validation\annotation\Validate;

class DemoController
{
    #[Validate(rules: [
        'content' => 'required|string',
        'uid' => 'required|integer',
    ])]
    public function create(string $content, int $uid)
    {
    }
}
```

2. Only partial rules provided, the rest is inferred:

```
use support\validation\annotation\Validate;

class DemoController
{
    #[Validate(rules: [
        'content' => 'min:2',
    ])]
    public function create(string $content, int $uid)
    {
    }
}
```

Equivalent to:

```
use support\validation\annotation\Validate;

class DemoController
{
    #[Validate(rules: [
        'content' => 'required|string|min:2',
        'uid' => 'required|integer',
    ])]
    public function create(string $content, int $uid)
    {
    }
}
```

3. Default values / nullable types:

```
use support\validation\annotation\Validate;

class DemoController
{
    #[Validate]
    public function create(string $content = 'default', ?int $uid = null)
    {
    }
}
```

Equivalent to:

```
use support\validation\annotation\Validate;

class DemoController
{
    #[Validate(rules: [
        'content' => 'string',
        'uid' => 'integer|nullable',
    ])]
    public function create(string $content = 'default', ?int $uid = null)
    {
    }
}
```

Exception Handling
------------------

[](#exception-handling)

### Default Exception

[](#default-exception)

Validation failure throws `support\validation\ValidationException`, which inherits from `Webman\Exception\BusinessException` and does not log errors.

Default response behavior is handled by `BusinessException::render()`:

- Non-JSON requests: return a plain string message, e.g. `token is required.`
- JSON requests: return JSON response, e.g. `{"code": 422, "msg": "token is required.", "data":....}`

### Customize with a custom exception

[](#customize-with-a-custom-exception)

- Global config: `exception` in `config/plugin/webman/validation/app.php`

Multi-Language Support
----------------------

[](#multi-language-support)

The component includes built-in Chinese and English language packs and supports project overrides. Loading order:

1. Project language pack `resource/translations/{locale}/validation.php`
2. Component built-in `vendor/webman/validation/resources/lang/{locale}/validation.php`
3. Illuminate built-in English (fallback)

> **Note**
> The default language of webman is configured in `config/translation.php`, and it can also be changed using the function `locale('en');`.

### Local Override Example

[](#local-override-example)

`resource/translations/en/validation.php`

```
return [
    'email' => 'The :attribute is not a valid email format.',
];
```

Middleware Auto-Loading
-----------------------

[](#middleware-auto-loading)

After installation, the component automatically loads the validation middleware via `config/plugin/webman/validation/middleware.php`, no manual registration required.

CLI Generator
-------------

[](#cli-generator)

Use `make:validator` to generate a validator class (generated under `app/validation` by default).

> **Tip**
> You need to install `composer require webman/console`

### Basic

[](#basic)

- **Generate an empty template**

```
php webman make:validator UserValidator
```

- **Overwrite if the file already exists**

```
php webman make:validator UserValidator --force
php webman make:validator UserValidator -f
```

### Generate rules from a table

[](#generate-rules-from-a-table)

- **Generate rules from a table schema** (infers `$rules` from column type/nullability/length; default excluded columns depend on ORM: laravel uses `created_at/updated_at/deleted_at`, thinkorm uses `create_time/update_time/delete_time`)

```
php webman make:validator UserValidator --table=wa_users
php webman make:validator UserValidator -t wa_users
```

- **Select a database connection** (multi-connection)

```
php webman make:validator UserValidator --table=wa_users --database=mysql
php webman make:validator UserValidator -t wa_users -d mysql
```

### Scenes

[](#scenes)

- **Generate CRUD scenes**: `create/update/delete/detail`

```
php webman make:validator UserValidator --table=wa_users --scenes=crud
php webman make:validator UserValidator -t wa_users -s crud
```

> The `update` scene includes the primary key (to locate the record) plus the other fields; `delete/detail` include only primary key fields by default.

### ORM selection (laravel(illuminate/database) vs think-orm)

[](#orm-selection-laravelilluminatedatabase-vs-think-orm)

- **Auto (default)**: uses the available ORM; if both exist, defaults to illuminate
- **Force**

```
php webman make:validator UserValidator --table=wa_users --orm=laravel
php webman make:validator UserValidator --table=wa_users --orm=thinkorm
php webman make:validator UserValidator -t wa_users -o thinkorm
```

### Example

[](#example)

```
php webman make:validator UserValidator -t wa_users -d mysql -s crud -o laravel -f
```

Unit Testing
------------

[](#unit-testing)

Enter the `webman/validation` root directory and execute:

```
composer install
vendor\bin\phpunit -c phpunit.xml
```

All Validation Rules Reference
------------------------------

[](#all-validation-rules-reference)

Available Validation Rules
--------------------------

[](#available-validation-rules)

Important

- Webman Validation is based on `illuminate/validation`, with rule names consistent with Laravel, and the rules themselves have no Webman-specific modifications.
- The middleware validates data from `$request->all()` (GET+POST) by default and merges route parameters, excluding uploaded files; for file-related rules, manually merge `$request->file()` into the data or call `Validator::make` manually.
- `current_password` depends on authentication guards, `exists`/`unique` depend on database connections and query builders, and these rules are unavailable without integrating the corresponding components.

The following lists all available validation rules and their functions:

&lt;style&gt; .collection-method-list &gt; p { columns: 10.8em 3; -moz-columns: 10.8em 3; -webkit-columns: 10.8em 3; } .collection-method-list a { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } &lt;/style&gt; #### Boolean Values

[](#boolean-values)

[Accepted](#rule-accepted)[Accepted If](#rule-accepted-if)[Boolean](#rule-boolean)[Declined](#rule-declined)[Declined If](#rule-declined-if)

#### Strings

[](#strings)

[Active URL](#rule-active-url)[Alpha](#rule-alpha)[Alpha Dash](#rule-alpha-dash)[Alpha Numeric](#rule-alpha-num)[Ascii](#rule-ascii)[Confirmed](#rule-confirmed)[Current Password](#rule-current-password)[Different](#rule-different)[Doesnt Start With](#rule-doesnt-start-with)[Doesnt End With](#rule-doesnt-end-with)[Email](#rule-email)[Ends With](#rule-ends-with)[Enum](#rule-enum)[Hex Color](#rule-hex-color)[In](#rule-in)[IP Address](#rule-ip)[IPv4](#rule-ipv4)[IPv6](#rule-ipv6)[JSON](#rule-json)[Lowercase](#rule-lowercase)[MAC Address](#rule-mac)[Max](#rule-max)[Min](#rule-min)[Not In](#rule-not-in)[Regular Expression](#rule-regex)[Not Regular Expression](#rule-not-regex)[Same](#rule-same)[Size](#rule-size)[Starts With](#rule-starts-with)[String](#rule-string)[Uppercase](#rule-uppercase)[URL](#rule-url)[ULID](#rule-ulid)[UUID](#rule-uuid)

#### Numbers

[](#numbers)

[Between](#rule-between)[Decimal](#rule-decimal)[Different](#rule-different)[Digits](#rule-digits)[Digits Between](#rule-digits-between)[Greater Than](#rule-gt)[Greater Than Or Equal](#rule-gte)[Integer](#rule-integer)[Less Than](#rule-lt)[Less Than Or Equal](#rule-lte)[Max](#rule-max)[Max Digits](#rule-max-digits)[Min](#rule-min)[Min Digits](#rule-min-digits)[Multiple Of](#rule-multiple-of)[Numeric](#rule-numeric)[Same](#rule-same)[Size](#rule-size)

#### Arrays

[](#arrays)

[Array](#rule-array)[Between](#rule-between)[Contains](#rule-contains)[Doesnt Contain](#rule-doesnt-contain)[Distinct](#rule-distinct)[In Array](#rule-in-array)[In Array Keys](#rule-in-array-keys)[List](#rule-list)[Max](#rule-max)[Min](#rule-min)[Size](#rule-size)

#### Dates

[](#dates)

[After](#rule-after)[After Or Equal](#rule-after-or-equal)[Before](#rule-before)[Before Or Equal](#rule-before-or-equal)[Date](#rule-date)[Date Equals](#rule-date-equals)[Date Format](#rule-date-format)[Different](#rule-different)[Timezone](#rule-timezone)

#### Files

[](#files)

[Between](#rule-between)[Dimensions](#rule-dimensions)[Encoding](#rule-encoding)[Extensions](#rule-extensions)[File](#rule-file)[Image](#rule-image)[Max](#rule-max)[MIME Types](#rule-mimetypes)[MIME Type By File Extension](#rule-mimes)[Size](#rule-size)

#### Database

[](#database)

[Exists](#rule-exists)[Unique](#rule-unique)

#### Utilities

[](#utilities)

[Any Of](#rule-anyof)[Bail](#rule-bail)[Exclude](#rule-exclude)[Exclude If](#rule-exclude-if)[Exclude Unless](#rule-exclude-unless)[Exclude With](#rule-exclude-with)[Exclude Without](#rule-exclude-without)[Filled](#rule-filled)[Missing](#rule-missing)[Missing If](#rule-missing-if)[Missing Unless](#rule-missing-unless)[Missing With](#rule-missing-with)[Missing With All](#rule-missing-with-all)[Nullable](#rule-nullable)[Present](#rule-present)[Present If](#rule-present-if)[Present Unless](#rule-present-unless)[Present With](#rule-present-with)[Present With All](#rule-present-with-all)[Prohibited](#rule-prohibited)[Prohibited If](#rule-prohibited-if)[Prohibited If Accepted](#rule-prohibited-if-accepted)[Prohibited If Declined](#rule-prohibited-if-declined)[Prohibited Unless](#rule-prohibited-unless)[Prohibits](#rule-prohibits)[Required](#rule-required)[Required If](#rule-required-if)[Required If Accepted](#rule-required-if-accepted)[Required If Declined](#rule-required-if-declined)[Required Unless](#rule-required-unless)[Required With](#rule-required-with)[Required With All](#rule-required-with-all)[Required Without](#rule-required-without)[Required Without All](#rule-required-without-all)[Required Array Keys](#rule-required-array-keys)[Sometimes](#validating-when-present)

#### accepted

[](#accepted)

The field under validation must be `"yes"`, `"on"`, `1`, `"1"`, `true`, or `"true"`. This is commonly used for scenarios like confirming agreement to terms of service.

#### accepted\_if:anotherfield,value,...

[](#accepted_ifanotherfieldvalue)

The field under validation must be `"yes"`, `"on"`, `1`, `"1"`, `true`, or `"true"` when another field equals the specified value. This is useful for conditional agreement scenarios.

#### active\_url

[](#active_url)

The field under validation must have a valid A or AAAA record. The rule first extracts the hostname using `parse_url` and then validates it with `dns_get_record`.

#### after:*date*

[](#afterdate)

The field under validation must be a value after the given date. The date is converted to a valid `DateTime` using `strtotime`:

```
use support\validation\Validator;

Validator::make($data, [
    'start_date' => 'required|date|after:tomorrow',
])->validate();
```

You can also pass another field name for comparison:

```
Validator::make($data, [
    'finish_date' => 'required|date|after:start_date',
])->validate();
```

You can use the fluent `date` rule builder:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'start_date' => [
        'required',
        Rule::date()->after(\Carbon\Carbon::today()->addDays(7)),
    ],
])->validate();
```

`afterToday` and `todayOrAfter` can conveniently express "must be after today" or "must be today or later":

```
Validator::make($data, [
    'start_date' => [
        'required',
        Rule::date()->afterToday(),
    ],
])->validate();
```

#### after\_or\_equal:*date*

[](#after_or_equaldate)

The field under validation must be after or equal to the given date. For more details, see the [after](#rule-after) rule.

You can use the fluent `date` rule builder:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'start_date' => [
        'required',
        Rule::date()->afterOrEqual(\Carbon\Carbon::today()->addDays(7)),
    ],
])->validate();
```

#### anyOf

[](#anyof)

`Rule::anyOf` allows specifying "pass if any one of the rule sets is satisfied". For example, the following rule means `username` is either an email address or an alphanumeric string with underscores/dashes of at least 6 characters:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'username' => [
        'required',
        Rule::anyOf([
            ['string', 'email'],
            ['string', 'alpha_dash', 'min:6'],
        ]),
    ],
])->validate();
```

#### alpha

[](#alpha)

The field under validation must consist of Unicode letters ([\\p{L}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=) and [\\p{M}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=)).

To allow only ASCII (`a-z`, `A-Z`), add the `ascii` option:

```
Validator::make($data, [
    'username' => 'alpha:ascii',
])->validate();
```

#### alpha\_dash

[](#alpha_dash)

The field under validation can only contain Unicode alphanumeric characters ([\\p{L}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=), [\\p{M}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=), [\\p{N}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AN%3A%5D&g=&i=)), as well as ASCII dashes (`-`) and underscores (`_`).

To allow only ASCII (`a-z`, `A-Z`, `0-9`), add the `ascii` option:

```
Validator::make($data, [
    'username' => 'alpha_dash:ascii',
])->validate();
```

#### alpha\_num

[](#alpha_num)

The field under validation can only contain Unicode alphanumeric characters ([\\p{L}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AL%3A%5D&g=&i=), [\\p{M}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AM%3A%5D&g=&i=), [\\p{N}](https://util.unicode.org/UnicodeJsps/list-unicodeset.jsp?a=%5B%3AN%3A%5D&g=&i=)).

To allow only ASCII (`a-z`, `A-Z`, `0-9`), add the `ascii` option:

```
Validator::make($data, [
    'username' => 'alpha_num:ascii',
])->validate();
```

#### array

[](#array)

The field under validation must be a PHP `array`.

When the `array` rule includes additional parameters, the keys in the input array must be in the parameter list. In the example, the `admin` key is not in the allowed list, so it is invalid:

```
use support\validation\Validator;

$input = [
    'user' => [
        'name' => 'Taylor Otwell',
        'username' => 'taylorotwell',
        'admin' => true,
    ],
];

Validator::make($input, [
    'user' => 'array:name,username',
])->validate();
```

It is recommended to explicitly specify the allowed keys for arrays in actual projects.

#### ascii

[](#ascii)

The field under validation can only contain 7-bit ASCII characters.

#### bail

[](#bail)

When the first validation rule for a field fails, stop validating the other rules for that field.

This rule only affects the current field. For "stop on first failure globally", use Illuminate's validator directly and call `stopOnFirstFailure()`.

#### before:*date*

[](#beforedate)

The field under validation must be before the given date. The date is converted to a valid `DateTime` using `strtotime`. Similar to the [after](#rule-after) rule, you can pass another field name for comparison.

You can use the fluent `date` rule builder:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'start_date' => [
        'required',
        Rule::date()->before(\Carbon\Carbon::today()->subDays(7)),
    ],
])->validate();
```

`beforeToday` and `todayOrBefore` can conveniently express "must be before today" or "must be today or earlier":

```
Validator::make($data, [
    'start_date' => [
        'required',
        Rule::date()->beforeToday(),
    ],
])->validate();
```

#### before\_or\_equal:*date*

[](#before_or_equaldate)

The field under validation must be before or equal to the given date. The date is converted to a valid `DateTime` using `strtotime`. Similar to the [after](#rule-after) rule, you can pass another field name for comparison.

You can use the fluent `date` rule builder:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'start_date' => [
        'required',
        Rule::date()->beforeOrEqual(\Carbon\Carbon::today()->subDays(7)),
    ],
])->validate();
```

#### between:*min*,*max*

[](#betweenminmax)

The field under validation must have a size between the given *min* and *max* (inclusive). Strings, numbers, arrays, and files are evaluated using the same rules as [size](#rule-size).

#### boolean

[](#boolean)

The field under validation must be convertible to a boolean value. Acceptable inputs include `true`, `false`, `1`, `0`, `"1"`, `"0"`.

You can use the `strict` parameter to allow only `true` or `false`:

```
Validator::make($data, [
    'foo' => 'boolean:strict',
])->validate();
```

#### confirmed

[](#confirmed)

The field under validation must have a matching field `{field}_confirmation`. For example, if the field is `password`, `password_confirmation` is required.

You can also specify a custom confirmation field name, such as `confirmed:repeat_username`, which requires `repeat_username` to match the current field.

#### contains:*foo*,*bar*,...

[](#containsfoobar)

The field under validation must be an array and must contain all the given parameter values. This rule is often used for array validation and can be constructed using `Rule::contains`:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'roles' => [
        'required',
        'array',
        Rule::contains(['admin', 'editor']),
    ],
])->validate();
```

#### doesnt\_contain:*foo*,*bar*,...

[](#doesnt_containfoobar)

The field under validation must be an array and must not contain any of the given parameter values. You can use `Rule::doesntContain` to construct:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'roles' => [
        'required',
        'array',
        Rule::doesntContain(['admin', 'editor']),
    ],
])->validate();
```

#### current\_password

[](#current_password)

The field under validation must match the current authenticated user's password. You can specify the authentication guard via the first parameter:

```
Validator::make($data, [
    'password' => 'current_password:api',
])->validate();
```

Warning

This rule depends on the authentication component and guard configuration; do not use it without integrating authentication.

#### date

[](#date)

The field under validation must be a valid (non-relative) date recognized by `strtotime`.

#### date\_equals:*date*

[](#date_equalsdate)

The field under validation must equal the given date. The date is converted to a valid `DateTime` using `strtotime`.

#### date\_format:*format*,...

[](#date_formatformat)

The field under validation must match one of the given formats. Use either `date` or `date_format`. This rule supports all formats of PHP [DateTime](https://www.php.net/manual/en/class.datetime.php).

You can use the fluent `date` rule builder:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'start_date' => [
        'required',
        Rule::date()->format('Y-m-d'),
    ],
])->validate();
```

#### decimal:*min*,*max*

[](#decimalminmax)

The field under validation must be a number with the specified number of decimal places:

```
Validator::make($data, [
    'price' => 'decimal:2',
])->validate();

Validator::make($data, [
    'price' => 'decimal:2,4',
])->validate();
```

#### declined

[](#declined)

The field under validation must be `"no"`, `"off"`, `0`, `"0"`, `false`, or `"false"`.

#### declined\_if:anotherfield,value,...

[](#declined_ifanotherfieldvalue)

The field under validation must be `"no"`, `"off"`, `0`, `"0"`, `false`, or `"false"` when another field equals the specified value.

#### different:*field*

[](#differentfield)

The field under validation must be different from *field*.

#### digits:*value*

[](#digitsvalue)

The field under validation must be an integer with a length of *value*.

#### digits\_between:*min*,*max*

[](#digits_betweenminmax)

The field under validation must be an integer with a length between *min* and *max*.

#### dimensions

[](#dimensions)

The field under validation must be an image and satisfy the dimension constraints:

```
Validator::make($data, [
    'avatar' => 'dimensions:min_width=100,min_height=200',
])->validate();
```

Available constraints: *min\_width*, *max\_width*, *min\_height*, *max\_height*, *width*, *height*, *ratio*.

*ratio* is the aspect ratio, which can be expressed as a fraction or float:

```
Validator::make($data, [
    'avatar' => 'dimensions:ratio=3/2',
])->validate();
```

Due to the many parameters in this rule, it is recommended to use `Rule::dimensions` to construct:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()
            ->maxWidth(1000)
            ->maxHeight(500)
            ->ratio(3 / 2),
    ],
])->validate();
```

#### distinct

[](#distinct)

When validating an array, the field values must not be duplicated:

```
Validator::make($data, [
    'foo.*.id' => 'distinct',
])->validate();
```

By default, loose comparison is used. For strict comparison, add `strict`:

```
Validator::make($data, [
    'foo.*.id' => 'distinct:strict',
])->validate();
```

You can add `ignore_case` to ignore case differences:

```
Validator::make($data, [
    'foo.*.id' => 'distinct:ignore_case',
])->validate();
```

#### doesnt\_start\_with:*foo*,*bar*,...

[](#doesnt_start_withfoobar)

The field under validation must not start with the specified values.

#### doesnt\_end\_with:*foo*,*bar*,...

[](#doesnt_end_withfoobar)

The field under validation must not end with the specified values.

#### email

[](#email)

The field under validation must be a valid email address. This rule relies on [egulias/email-validator](https://github.com/egulias/EmailValidator), defaulting to `RFCValidation`, but other validation methods can be specified:

```
Validator::make($data, [
    'email' => 'email:rfc,dns',
])->validate();
```

Available validation methods:

- `rfc`: `RFCValidation` - Validates email according to RFC standards ([supported RFCs](https://github.com/egulias/EmailValidator?tab=readme-ov-file#supported-rfcs)).
- `strict`: `NoRFCWarningsValidation` - Fails on warnings during RFC validation (e.g., trailing dots or consecutive dots).
- `dns`: `DNSCheckValidation` - Checks if the domain has a valid MX record.
- `spoof`: `SpoofCheckValidation` - Prevents homoglyph or deceptive Unicode characters.
- `filter`: `FilterEmailValidation` - Validates using PHP `filter_var`.
- `filter_unicode`: `FilterEmailValidation::unicode()` - Unicode-allowed `filter_var` validation.

You can use the fluent rule builder:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'email' => [
        'required',
        Rule::email()
            ->rfcCompliant(strict: false)
            ->validateMxRecord()
            ->preventSpoofing(),
    ],
])->validate();
```

Warning

`dns` and `spoof` require the PHP `intl` extension.

#### encoding:*encoding\_type*

[](#encodingencoding_type)

The field under validation must match the specified character encoding. This rule uses `mb_check_encoding` to detect the encoding of files or strings. It can be used with the file rule builder:

```
use Illuminate\Validation\Rules\File;
use support\validation\Validator;

Validator::make($data, [
    'attachment' => [
        'required',
        File::types(['csv'])->encoding('utf-8'),
    ],
])->validate();
```

#### ends\_with:*foo*,*bar*,...

[](#ends_withfoobar)

The field under validation must end with one of the specified values.

#### enum

[](#enum)

`Enum` is a class-based rule used to validate if the field value is a valid enum value. Pass the enum class name during construction. For validating basic type values, use Backed Enum:

```
use app\enums\ServerStatus;
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'status' => [Rule::enum(ServerStatus::class)],
])->validate();
```

You can use `only`/`except` to restrict enum values:

```
use app\enums\ServerStatus;
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'status' => [
        Rule::enum(ServerStatus::class)
            ->only([ServerStatus::Pending, ServerStatus::Active]),
    ],
])->validate();

Validator::make($data, [
    'status' => [
        Rule::enum(ServerStatus::class)
            ->except([ServerStatus::Pending, ServerStatus::Active]),
    ],
])->validate();
```

You can use `when` for conditional restrictions:

```
use app\Enums\ServerStatus;
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'status' => [
        Rule::enum(ServerStatus::class)->when(
            $isAdmin,
            fn ($rule) => $rule->only(ServerStatus::Active),
            fn ($rule) => $rule->only(ServerStatus::Pending),
        ),
    ],
])->validate();
```

#### exclude

[](#exclude)

The field under validation will be excluded from the data returned by `validate`/`validated`.

#### exclude\_if:*anotherfield*,*value*

[](#exclude_ifanotherfieldvalue)

The field under validation will be excluded from the data returned by `validate`/`validated` when *anotherfield* equals *value*.

For complex conditions, use `Rule::excludeIf`:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'role_id' => Rule::excludeIf($isAdmin),
])->validate();

Validator::make($data, [
    'role_id' => Rule::excludeIf(fn () => $isAdmin),
])->validate();
```

#### exclude\_unless:*anotherfield*,*value*

[](#exclude_unlessanotherfieldvalue)

The field under validation will be excluded from the data returned by `validate`/`validated` unless *anotherfield* equals *value*. If *value* is `null` (e.g., `exclude_unless:name,null`), the field is retained only if the comparison field is `null` or does not exist.

#### exclude\_with:*anotherfield*

[](#exclude_withanotherfield)

The field under validation will be excluded from the data returned by `validate`/`validated` when *anotherfield* exists.

#### exclude\_without:*anotherfield*

[](#exclude_withoutanotherfield)

The field under validation will be excluded from the data returned by `validate`/`validated` when *anotherfield* does not exist.

#### exists:*table*,*column*

[](#existstablecolumn)

The field under validation must exist in the specified database table.

#### Basic Usage of Exists Rule

[](#basic-usage-of-exists-rule)

```
Validator::make($data, [
    'state' => 'exists:states',
])->validate();
```

If `column` is not specified, the field name is used by default. Thus, this example validates if the `state` column exists in the `states` table.

#### Specifying a Custom Column Name

[](#specifying-a-custom-column-name)

You can append the column name after the table name:

```
Validator::make($data, [
    'state' => 'exists:states,abbreviation',
])->validate();
```

To specify a database connection, prepend the connection name to the table:

```
Validator::make($data, [
    'email' => 'exists:connection.staff,email',
])->validate();
```

You can also pass a model class name, and the framework will resolve the table name:

```
Validator::make($data, [
    'user_id' => 'exists:app\model\User,id',
])->validate();
```

To customize query conditions, use the `Rule` rule builder:

```
use Illuminate\Database\Query\Builder;
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'email' => [
        'required',
        Rule::exists('staff')->where(function (Builder $query) {
            $query->where('account_id', 1);
        }),
    ],
])->validate();
```

You can also specify the column name directly in `Rule::exists`:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'state' => [Rule::exists('states', 'abbreviation')],
])->validate();
```

When validating if a group of values exists, combine with the `array` rule:

```
Validator::make($data, [
    'states' => ['array', Rule::exists('states', 'abbreviation')],
])->validate();
```

When `array` and `exists` coexist, a single query is generated to validate all values.

#### extensions:*foo*,*bar*,...

[](#extensionsfoobar)

The uploaded file's extension must be in the allowed list:

```
Validator::make($data, [
    'photo' => ['required', 'extensions:jpg,png'],
])->validate();
```

Warning

Do not rely solely on extension validation for file types; it is recommended to use it with [mimes](#rule-mimes) or [mimetypes](#rule-mimetypes).

#### file

[](#file)

The field under validation must be a successfully uploaded file.

#### filled

[](#filled)

When the field exists, its value must not be empty.

#### gt:*field*

[](#gtfield)

The field under validation must be greater than the given *field* or *value*. The two fields must be of the same type. Strings, numbers, arrays, and files are evaluated using the same rules as [size](#rule-size).

#### gte:*field*

[](#gtefield)

The field under validation must be greater than or equal to the given *field* or *value*. The two fields must be of the same type. Strings, numbers, arrays, and files are evaluated using the same rules as [size](#rule-size).

#### hex\_color

[](#hex_color)

The field under validation must be a valid [hexadecimal color value](https://developer.mozilla.org/en-US/docs/Web/CSS/hex-color).

#### image

[](#image)

The field under validation must be an image (jpg, jpeg, png, bmp, gif, or webp).

Warning

SVG is not allowed by default due to XSS risks. To allow it, add `allow_svg`: `image:allow_svg`.

#### in:*foo*,*bar*,...

[](#infoobar)

The field under validation must be in the given list of values. You can use `Rule::in` to construct:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'zones' => [
        'required',
        Rule::in(['first-zone', 'second-zone']),
    ],
])->validate();
```

When combined with the `array` rule, every value in the input array must be in the `in` list:

```
use support\validation\Rule;
use support\validation\Validator;

$input = [
    'airports' => ['NYC', 'LAS'],
];

Validator::make($input, [
    'airports' => [
        'required',
        'array',
    ],
    'airports.*' => Rule::in(['NYC', 'LIT']),
])->validate();
```

#### in\_array:*anotherfield*.\*

[](#in_arrayanotherfield)

The field under validation must exist in the value list of *anotherfield*.

#### in\_array\_keys:*value*.\*

[](#in_array_keysvalue)

The field under validation must be an array and must contain at least one of the given values as a key:

```
Validator::make($data, [
    'config' => 'array|in_array_keys:timezone',
])->validate();
```

#### integer

[](#integer)

The field under validation must be an integer.

You can use the `strict` parameter to require the field type to be integer; string representations of integers will be considered invalid:

```
Validator::make($data, [
    'age' => 'integer:strict',
])->validate();
```

Warning

This rule only checks if it passes PHP's `FILTER_VALIDATE_INT`; to enforce numeric types, use it with [numeric](#rule-numeric).

#### ip

[](#ip)

The field under validation must be a valid IP address.

#### ipv4

[](#ipv4)

The field under validation must be a valid IPv4 address.

#### ipv6

[](#ipv6)

The field under validation must be a valid IPv6 address.

#### json

[](#json)

The field under validation must be a valid JSON string.

#### lt:*field*

[](#ltfield)

The field under validation must be less than the given *field*. The two fields must be of the same type. Strings, numbers, arrays, and files are evaluated using the same rules as [size](#rule-size).

#### lte:*field*

[](#ltefield)

The field under validation must be less than or equal to the given *field*. The two fields must be of the same type. Strings, numbers, arrays, and files are evaluated using the same rules as [size](#rule-size).

#### lowercase

[](#lowercase)

The field under validation must be lowercase.

#### list

[](#list)

The field under validation must be a list array. The keys in a list array must be consecutive numbers from 0 to `count($array) - 1`.

#### mac\_address

[](#mac_address)

The field under validation must be a valid MAC address.

#### max:*value*

[](#maxvalue)

The field under validation must be less than or equal to *value*. Strings, numbers, arrays, and files are evaluated using the same rules as [size](#rule-size).

#### max\_digits:*value*

[](#max_digitsvalue)

The field under validation must be an integer with a length not exceeding *value*.

#### mimetypes:*text/plain*,...

[](#mimetypestextplain)

The file's MIME type must be in the list:

```
Validator::make($data, [
    'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime',
])->validate();
```

The MIME type is guessed by reading the file content, which may differ from the client-provided MIME.

#### mimes:*foo*,*bar*,...

[](#mimesfoobar)

The file's MIME type must correspond to the given extension:

```
Validator::make($data, [
    'photo' => 'mimes:jpg,bmp,png',
])->validate();
```

Although the parameters are extensions, this rule reads the file content to determine the MIME. The extension-to-MIME mapping is from:

#### MIME Types and Extensions

[](#mime-types-and-extensions)

This rule does not validate if the "filename extension" matches the "actual MIME". For example, `mimes:png` will consider `photo.txt` with PNG content as valid. To validate extensions, use [extensions](#rule-extensions).

#### min:*value*

[](#minvalue)

The field under validation must be greater than or equal to *value*. Strings, numbers, arrays, and files are evaluated using the same rules as [size](#rule-size).

#### min\_digits:*value*

[](#min_digitsvalue)

The field under validation must be an integer with a length of at least *value*.

#### multiple\_of:*value*

[](#multiple_ofvalue)

The field under validation must be a multiple of *value*.

#### missing

[](#missing)

The field under validation must not exist in the input data.

#### missing\_if:*anotherfield*,*value*,...

[](#missing_ifanotherfieldvalue)

The field under validation must not exist when *anotherfield* equals any *value*.

#### missing\_unless:*anotherfield*,*value*

[](#missing_unlessanotherfieldvalue)

The field under validation must not exist unless *anotherfield* equals any *value*.

#### missing\_with:*foo*,*bar*,...

[](#missing_withfoobar)

The field under validation must not exist when any of the specified fields exist.

#### missing\_with\_all:*foo*,*bar*,...

[](#missing_with_allfoobar)

The field under validation must not exist when all specified fields exist.

#### not\_in:*foo*,*bar*,...

[](#not_infoobar)

The field under validation must not be in the given list of values. You can use `Rule::notIn` to construct:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'toppings' => [
        'required',
        Rule::notIn(['sprinkles', 'cherries']),
    ],
])->validate();
```

#### not\_regex:*pattern*

[](#not_regexpattern)

The field under validation must not match the given regular expression.

This rule uses PHP `preg_match`. The regex must include delimiters, e.g., `'email' => 'not_regex:/^.+$/i'`.

Warning

When using `regex` / `not_regex`, if the regex contains `|`, it is recommended to declare rules in array form to avoid conflicts with the `|` separator.

#### nullable

[](#nullable)

The field under validation may be `null`.

#### numeric

[](#numeric)

The field under validation must be [numeric](https://www.php.net/manual/en/function.is-numeric.php).

You can use the `strict` parameter to allow only integer or float types; numeric strings will be considered invalid:

```
Validator::make($data, [
    'amount' => 'numeric:strict',
])->validate();
```

#### present

[](#present)

The field under validation must exist in the input data.

#### present\_if:*anotherfield*,*value*,...

[](#present_ifanotherfieldvalue)

The field under validation must exist when *anotherfield* equals any *value*.

#### present\_unless:*anotherfield*,*value*

[](#present_unlessanotherfieldvalue)

The field under validation must exist unless *anotherfield* equals any *value*.

#### present\_with:*foo*,*bar*,...

[](#present_withfoobar)

The field under validation must exist when any of the specified fields exist.

#### present\_with\_all:*foo*,*bar*,...

[](#present_with_allfoobar)

The field under validation must exist when all specified fields exist.

#### prohibited

[](#prohibited)

The field under validation must be missing or empty. A field is "empty" if:

- The value is `null`.
- The value is an empty string.
- The value is an empty array or empty `Countable` object.
- It is an uploaded file with an empty path.

#### prohibited\_if:*anotherfield*,*value*,...

[](#prohibited_ifanotherfieldvalue)

The field under validation must be missing or empty when *anotherfield* equals any *value*. A field is "empty" if:

- The value is `null`.
- The value is an empty string.
- The value is an empty array or empty `Countable` object.
- It is an uploaded file with an empty path.

For complex conditions, use `Rule::prohibitedIf`:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'role_id' => Rule::prohibitedIf($isAdmin),
])->validate();

Validator::make($data, [
    'role_id' => Rule::prohibitedIf(fn () => $isAdmin),
])->validate();
```

#### prohibited\_if\_accepted:*anotherfield*,...

[](#prohibited_if_acceptedanotherfield)

The field under validation must be missing or empty when *anotherfield* is `"yes"`, `"on"`, `1`, `"1"`, `true`, or `"true"`.

#### prohibited\_if\_declined:*anotherfield*,...

[](#prohibited_if_declinedanotherfield)

The field under validation must be missing or empty when *anotherfield* is `"no"`, `"off"`, `0`, `"0"`, `false`, or `"false"`.

#### prohibited\_unless:*anotherfield*,*value*,...

[](#prohibited_unlessanotherfieldvalue)

The field under validation must be missing or empty unless *anotherfield* equals any *value*. A field is "empty" if:

- The value is `null`.
- The value is an empty string.
- The value is an empty array or empty `Countable` object.
- It is an uploaded file with an empty path.

#### prohibits:*anotherfield*,...

[](#prohibitsanotherfield)

When the field under validation exists and is not empty, all fields in *anotherfield* must be missing or empty. A field is "empty" if:

- The value is `null`.
- The value is an empty string.
- The value is an empty array or empty `Countable` object.
- It is an uploaded file with an empty path.

#### regex:*pattern*

[](#regexpattern)

The field under validation must match the given regular expression.

This rule uses PHP `preg_match`. The regex must include delimiters, e.g., `'email' => 'regex:/^.+@.+$/i'`.

Warning

When using `regex` / `not_regex`, if the regex contains `|`, it is recommended to declare rules in array form to avoid conflicts with the `|` separator.

#### required

[](#required)

The field under validation must exist and not be empty. A field is "empty" if:

- The value is `null`.
- The value is an empty string.
- The value is an empty array or empty `Countable` object.
- It is an uploaded file with an empty path.

#### required\_if:*anotherfield*,*value*,...

[](#required_ifanotherfieldvalue)

The field under validation must exist and not be empty when *anotherfield* equals any *value*.

For complex conditions, use `Rule::requiredIf`:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'role_id' => Rule::requiredIf($isAdmin),
])->validate();

Validator::make($data, [
    'role_id' => Rule::requiredIf(fn () => $isAdmin),
])->validate();
```

#### required\_if\_accepted:*anotherfield*,...

[](#required_if_acceptedanotherfield)

The field under validation must exist and not be empty when *anotherfield* is `"yes"`, `"on"`, `1`, `"1"`, `true`, or `"true"`.

#### required\_if\_declined:*anotherfield*,...

[](#required_if_declinedanotherfield)

The field under validation must exist and not be empty when *anotherfield* is `"no"`, `"off"`, `0`, `"0"`, `false`, or `"false"`.

#### required\_unless:*anotherfield*,*value*,...

[](#required_unlessanotherfieldvalue)

The field under validation must exist and not be empty unless *anotherfield* equals any *value*. If *value* is `null` (e.g., `required_unless:name,null`), the field is allowed to be empty only if the comparison field is `null` or does not exist.

#### required\_with:*foo*,*bar*,...

[](#required_withfoobar)

The field under validation must exist and not be empty when any specified field exists and is not empty.

#### required\_with\_all:*foo*,*bar*,...

[](#required_with_allfoobar)

The field under validation must exist and not be empty when all specified fields exist and are not empty.

#### required\_without:*foo*,*bar*,...

[](#required_withoutfoobar)

The field under validation must exist and not be empty when any specified field is empty or does not exist.

#### required\_without\_all:*foo*,*bar*,...

[](#required_without_allfoobar)

The field under validation must exist and not be empty when all specified fields are empty or do not exist.

#### required\_array\_keys:*foo*,*bar*,...

[](#required_array_keysfoobar)

The field under validation must be an array and must contain at least the specified keys.

#### sometimes

[](#sometimes)

Apply subsequent validation rules only when the field exists. Commonly used for fields that are "optional but must be valid if present":

```
Validator::make($data, [
    'nickname' => 'sometimes|string|max:20',
])->validate();
```

#### same:*field*

[](#samefield)

The field under validation must be the same as *field*.

#### size:*value*

[](#sizevalue)

The field under validation must have a size equal to the given *value*. For strings, it is the character count; for numbers, it is the specified integer (use with `numeric` or `integer`); for arrays, it is the element count; for files, it is the size in KB. Example:

```
Validator::make($data, [
    'title' => 'size:12',
    'seats' => 'integer|size:10',
    'tags' => 'array|size:5',
    'image' => 'file|size:512',
])->validate();
```

#### starts\_with:*foo*,*bar*,...

[](#starts_withfoobar)

The field under validation must start with one of the specified values.

#### string

[](#string)

The field under validation must be a string. To allow `null`, use with `nullable`.

#### timezone

[](#timezone)

The field under validation must be a valid timezone identifier (from `DateTimeZone::listIdentifiers`). Parameters supported by this method can be passed:

```
Validator::make($data, [
    'timezone' => 'required|timezone:all',
])->validate();

Validator::make($data, [
    'timezone' => 'required|timezone:Africa',
])->validate();

Validator::make($data, [
    'timezone' => 'required|timezone:per_country,US',
])->validate();
```

#### unique:*table*,*column*

[](#uniquetablecolumn)

The field under validation must be unique in the specified table.

**Specifying Custom Table/Column Names:**

You can directly specify the model class name:

```
Validator::make($data, [
    'email' => 'unique:app\model\User,email_address',
])->validate();
```

You can specify the column name (defaults to the field name if not specified):

```
Validator::make($data, [
    'email' => 'unique:users,email_address',
])->validate();
```

**Specifying Database Connection:**

```
Validator::make($data, [
    'email' => 'unique:connection.users,email_address',
])->validate();
```

**Ignoring a Specific ID:**

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
])->validate();
```

Warning

`ignore` should not receive user input; only use system-generated unique IDs (auto-increment IDs or model UUIDs), otherwise there may be SQL injection risks.

You can also pass a model instance:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'email' => [
        Rule::unique('users')->ignore($user),
    ],
])->validate();
```

If the primary key is not `id`, specify the primary key name:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'email' => [
        Rule::unique('users')->ignore($user->id, 'user_id'),
    ],
])->validate();
```

By default, the field name is used as the unique column, but you can specify the column name:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'email' => [
        Rule::unique('users', 'email_address')->ignore($user->id),
    ],
])->validate();
```

**Adding Extra Conditions:**

```
use Illuminate\Database\Query\Builder;
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'email' => [
        Rule::unique('users')->where(
            fn (Builder $query) => $query->where('account_id', 1)
        ),
    ],
])->validate();
```

**Ignoring Soft-Deleted Records:**

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'email' => [Rule::unique('users')->withoutTrashed()],
])->validate();
```

If the soft-delete column name is not `deleted_at`:

```
use support\validation\Rule;
use support\validation\Validator;

Validator::make($data, [
    'email' => [Rule::unique('users')->withoutTrashed('was_deleted_at')],
])->validate();
```

#### uppercase

[](#uppercase)

The field under validation must be uppercase.

#### url

[](#url)

The field under validation must be a valid URL.

You can specify allowed protocols:

```
Validator::make($data, [
    'url' => 'url:http,https',
    'game' => 'url:minecraft,steam',
])->validate();
```

#### ulid

[](#ulid)

The field under validation must be a valid [ULID](https://github.com/ulid/spec).

#### uuid

[](#uuid)

The field under validation must be a valid RFC 9562 UUID (versions 1, 3, 4, 5, 6, 7, or 8).

You can specify the version:

```
Validator::make($data, [
    'uuid' => 'uuid:4',
])->validate();
```

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance84

Actively maintained with recent releases

Popularity23

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity35

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~4 days

Total

2

Last Release

82d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c8bc354ebf6983ed6334dd25ad0c1003b0034bcd148111d2d7ef463171f4dcba?d=identicon)[workerman](/maintainers/workerman)

---

Top Contributors

[![walkor](https://avatars.githubusercontent.com/u/6073368?v=4)](https://github.com/walkor "walkor (42 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/webman-validation/health.svg)

```
[![Health](https://phpackages.com/badges/webman-validation/health.svg)](https://phpackages.com/packages/webman-validation)
```

###  Alternatives

[livewire/livewire

A front-end framework for Laravel.

23.5k75.5M1.8k](/packages/livewire-livewire)[laravel/ui

Laravel UI utilities and presets.

2.7k134.9M601](/packages/laravel-ui)[propaganistas/laravel-phone

Adds phone number functionality to Laravel based on Google's libphonenumber API.

3.0k35.7M107](/packages/propaganistas-laravel-phone)[laravel/breeze

Minimal Laravel authentication scaffolding with Blade and Tailwind.

3.0k31.3M148](/packages/laravel-breeze)[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[laravel/lumen-framework

The Laravel Lumen Framework.

1.5k26.2M709](/packages/laravel-lumen-framework)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
