PHP code example of yuandian / validation

1. Go to this page and download the library: Download yuandian/validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yuandian / validation example snippets


use yuandian\rules\NotEmpty;
use yuandian\rules\Email;
use yuandian\rules\Scene;

// 用于配置场景验证
#[Scene("add",  ['name'])]
class UserRequest {
    #[NotEmpty(message: "Name cannot be empty.")]
    public string $name;

    #[Email(message: "Invalid email format.")]
    #[NotEmpty(message: "Email cannot be empty.")]
    public string $email;
}



use yuandian\Validation\Validator
use yuandian\Validation\Exception\ValidateException;

$request = new UserRequest();
$request->name = '张三';
$request->email = 'zhangsan@Validator'
// 验证实体
try {
    $validator = new Validator();
   
    $validator->validate($userRequest);
    // 批量验证
    // $validator->batch(true)->validate($userRequest);
    // 场景验证
    // $validator->validate($userRequest, 'add');
} catch (ValidateException $e) {
    echo "Validation errors: " . $e->getMessage() . "\n";
}

use yuandian\rules\NotEmpty;
use yuandian\rules\Email;
use yuandian\BaseValidatorEntity;

class UserRequest extends BaseValidatorEntity {
    #[NotEmpty(message: "Name cannot be empty.")]
    public string $name;

    #[Email(message: "Invalid email format.")]
    #[NotEmpty(message: "Email cannot be empty.")]
    public string $email;
}



use yuandian\Validation\Exception\ValidateException;

// 模拟请求数据
$requestData = [
    'name' => 'John Doe',
    'email' => 'invalid-email'
];

// 验证实体
try {
    $request = new UserRequest($requestData);
} catch (ValidateException $e) {
    echo "Validation errors: " . $e->getMessage() . "\n";
}
UserRequest.php
UserRequest.php