PHP code example of snow / validation

1. Go to this page and download the library: Download snow/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/ */

    

snow / validation example snippets


use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Alnum;

$validation = new Validation();
$validation->add('username', new Alnum());

$messages = $validation->validate([
    'username' => 'saas2;:sssaa'
]);

if (count($messages)) {
    foreach ($messages as $msg) {
        echo $msg, PHP_EOL;// username必须只包含字母和数字
        // echo $msg->getMessage(); // username必须只包含字母和数字
    }
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Alnum;

$validation = new Validation();
$validation->add('statistics.send.total_clicks', new Alnum([
    Alnum::OPT_MESSAGE => '统计点击数必须只包含字母和数字'
]));

/*$validation->add([
    'statistics.send.total_clicks',
    'statistics.send.total_exposure',
], new Alnum([
    Alnum::OPT_MESSAGE => [
        'statistics.send.total_clicks' => '统计点击数必须只包含字母和数字',
        'statistics.send.total_exposure' => '统计曝光必须只包含字母和数字',
    ]
]));*/

$messages = $validation->validate([
    'statistics' => [
        'send' => [
            'total_clicks' => 'aaa--',
            'total_exposure' => 'bbb'
        ]
    ]
]);

if (count($messages)) {
    foreach ($messages as $msg) {
         echo $msg->getMessage(); // 统计点击数必须只包含字母和数字
    }
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Alnum;

$validation = new Validation();
$validation->add('username', new Alnum([
    'message' => '字段:field必须只包含字母和数字'
]));

$group = $validation->validate([
    'username' => 'saas2;:s--'
]);
foreach ($group as $msg) {
    echo $msg; // 字段username必须只包含字母和数字
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Alnum;

$validation = new Validation();
$validation->add('username', new Alnum([
    'message' => ':field必须只包含字母和数字',
    'label' => '用户名',
]));

$group = $validation->validate([
    'username' => 'saas2;:s--'
]);
foreach ($group as $msg) {
    echo $msg, PHP_EOL; // 用户名必须只包含字母和数字
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Alnum;

$validation = new Validation();
$validation->add([
    'username',
    'name',
], new Alnum([
    'message' => [
        'username' => '字段1:field必须只包含字母和数字',
        'name' => '字段2:field必须只包含字母和数字',
    ]
]));

$group = $validation->validate([
    'username' => 'saas2;:s--',
    'name' => 'test--',
]);
foreach ($group as $msg) {
    echo $msg, PHP_EOL;
    // 字段1username必须只包含字母和数字
    // 字段2name必须只包含字母和数字
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Alnum;

$validation = new Validation();
$validation->add([
    'username',
    'name',
], new Alnum([
    'message' => [
        'username' => '字段1:field必须只包含字母和数字',
        'name' => '字段2:field必须只包含字母和数字',
    ],
    'allowEmpty' => true,
]));

$group = $validation->validate([
    'username' => 'saas2;:s--'
]);
foreach ($group as $msg) {
    echo $msg, PHP_EOL; // 字段1username必须只包含字母和数字
}



// 亦可指定空值
$validation = new Validation();
$validation->add([
    'username',
    'name',
], new Alnum([
    'message' => [
        'username' => '字段1:field必须只包含字母和数字',
        'name' => '字段2:field必须只包含字母和数字',
    ],
    // 指定空值
    'allowEmpty' => [0, false],
]));

$group = $validation->validate([
    'username' => 'saas2;:s--'
]);
foreach ($group as $msg) {
    echo $msg, PHP_EOL;
    // 字段1username必须只包含字母和数字
    // 字段2name必须只包含字母和数字
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Alnum;

$validation = new Validation();
$validation->add([
    'username',
    'name',
], new Alnum([
    'message' => [
        'username' => '字段1:field必须只包含字母和数字',
        'name' => '字段2:field必须只包含字母和数字',
    ],
    'cancelOnFail' => true
]));

$group = $validation->validate([
    'username' => 'saas2;:s--'
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL;
    // 字段1username必须只包含字母和数字
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Alnum;
use Snow\Validation\Validation\Validator\Alpha;

$validation = new Validation();
$validation->rules('username', [
    new Alnum(),
    new Alpha(),
]);

$group = $validation->validate(['username' => 'saas2;:s--']);

foreach ($group as $msg) {
    echo $msg, PHP_EOL;
    // username必须只包含字母和数字
    // username 必须只包含字母
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Alnum;
use Snow\Validation\Validation\Validator\Alpha;

$validation = new Validation();
// 设置默认提示
$validation->setDefaultMessages([
    Alnum::TYPE => ':field 只能为字母与数字',
    Alpha::TYPE => ':field 只能为字母',
]);
// 生成四条验证
$validation->rules([
    'username',
    'name',
], [
    new Alnum([
        'message' => [
            'username' => '用户名必须只包含字母和数字(我的优先级比较高)',
            'name' => '姓名必须只包含字母和数字(我的优先级比较高)',
        ]
    ]),
    new Alpha(),
]);

// 也可以这么写
/*$validation->rules([
    'username',
    'name',
], [
    new Alnum([
        'message' => ':field必须只包含字母和数字(我的优先级比较高)'
    ]),
    new Alpha(),
]);*/

$group = $validation->validate([
    'username' => 'saas2;:s--'
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL;
    // 用户名必须只包含字母和数字(我的优先级比较高)
    // 姓名必须只包含字母和数字(我的优先级比较高)
    // username 只能为字母
    // name 只能为字母
}

// 根据字段过滤消息
$messages = $group->filter('name');
foreach ($messages as $msg) {
    echo $msg, PHP_EOL;
}

namespace Test;

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Alnum;
use Snow\Validation\Validation\Validator\Alpha;
use Snow\Validation\Validation\Message;

class UserValidation extends Validation
{
    /**
     * 实例化时调用
     */
    public function initialize()
    {
//        $this->setDefaultMessages([
//            Alnum::TYPE => ':field 只能为字母与数字',
//            Alpha::TYPE => ':field 只能为字母',
//        ]);
        // 添加验证规则
        $this->add('username', new Alnum())
            ->add('name', new Alpha());
    }

    /**
     * 功能:验证之前调用,失败则取消验证
     * 修改日期:2019/8/13
     *
     * @param array|object $data 待验证数据
     * @param \Snow\Validation\Validation\Group $messages 验证消息
     * @return bool
     */
    public function beforeValidate($data, $messages)
    {
        if ($data['username'] == 'admin') {
            $messages->appendMessage(
                new Message('不允许注册admin')
            );
            return false;
        }
        return true;
    }

    /**
     * 功能:验证之后调用
     * 修改日期:2019/8/13
     *
     * @param array|object $data 待验证数据
     * @param \Snow\Validation\Validation\Group $messages 验证消息
     * @return void|mixed
     */
    public function afterValidate($data, $messages)
    {
    }
}


// 使用
$userValidation = new UserValidation();
$group = $userValidation->validate([
    'username' => 'admin'
]);

// beforeValidate返回false时validate才会返回false,其他场景下均返回\Snow\Validation\Validation\Group
// 如果没有自定义beforeValidate方法,或beforeValidate方法返回非false,可直接用count($group)来判断验证是否通过
if ($group === false) {
    $group = $userValidation->getMessages();
}
foreach ($group as $msg) {
    echo $msg; // 不允许注册admin
}


if (count($group)) {
    // 失败
    echo $group[0]->getMessage(); // 第一条错误消息
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Between;

$validation = new Validation();
$validation->add('age', new Between([
    Between::OPT_MAXIMUM => 90,
    Between::OPT_MINIMUM => 10,
    Between::OPT_MESSAGE => ':field 必须在:minimum到:maximum之间', // 非必须
]));

$group = $validation->validate([
    'age' => 9
]);
foreach ($group as $msg) {
    echo $msg->getMessage(), PHP_EOL;
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Callback;
use Snow\Validation\Validation\Validator\Alnum;

$validation = new Validation();
$validation->add('username', new Callback([
    Callback::OPT_CALLBACK => function ($data) {
        if ($data['username'] == 'admin') {
            return false;
        }
        return new Alnum();
    }
]));

$group = $validation->validate([
    'username' => 'saas2;:s--'
]);
foreach ($group as $msg) {
    echo $msg, PHP_EOL; // username必须只包含字母和数字
}

// 定义验证函数
function checkUsername($data)
{
    return $data['username'] == 'admin' ? false : true;
}

// 使用
use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Callback;

$validation = new Validation();
$validation->add('username', new Callback([
    Callback::OPT_CALLBACK => 'checkUsername'
]));

$group = $validation->validate([
    'username' => 'admin'
]);
foreach ($group as $msg) {
    echo $msg, PHP_EOL; // username验证失败
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Confirmation;

$validation = new Validation();
$validation->add('password', new Confirmation([
    Confirmation::OPT_WITH => 'confirmPassword',
    Confirmation::OPT_LABEL => '密码',
    Confirmation::OPT_LABEL_WITH => '确认密码',
]));

$group = $validation->validate([
    'password' => 'admin123',
    'confirmPassword' => 'Admin123',
]);
foreach ($group as $msg) {
    echo $msg, PHP_EOL; // 密码与确认密码必须相同
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Date;

$validation = new Validation();
$validation->add('strat_time', new Date([
    Date::OPT_FORMAT => 'Y-m-d H:i:s'
]));

$group = $validation->validate([
    'strat_time' => '2019-12-30'
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // strat_time不是有效的日期
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\ExclusionIn;

$validation = new Validation();
$validation->add(['hobbies', 'status'], new ExclusionIn([
    ExclusionIn::OPT_DOMAIN => [
        'hobbies' => ['足球', '篮球', '羽毛球', '乒乓球'],
        'status' => [0, 1, 2],
    ]
]));

$group = $validation->validate([
    'hobbies' => '乒乓球',
    'status' => '0'
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // hobbies必须不能在足球,篮球,羽毛球,乒乓球范围内
                        // status必须不能在0,1,2范围内
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\ExclusionIn;

$validation = new Validation();
$validation->add(['status', 'type'], new ExclusionIn([
    ExclusionIn::OPT_DOMAIN => [0, 1, 2],
    ExclusionIn::OPT_STRICT => true,
]));

$group = $validation->validate([
    'status' => '0',
    'type' => 0,
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // type必须不能在0,1,2范围内
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Identical;

$validation = new Validation();
$validation->add('terms', new Identical([
    Identical::OPT_ACCEPTED => 'yes'
]));

$group = $validation->validate([
    'terms' => 'no',
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // terms必须为yes
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\InclusionIn;

$validation = new Validation();
$validation->add('type', new InclusionIn([
    InclusionIn::OPT_DOMAIN => [1, 2, 3]
]));

$group = $validation->validate([
    'type' => 4,
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // type必须在1,2,3范围内
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Regex;

$validation = new Validation();
$validation->add('phone', new Regex([
    Regex::OPT_PATTERN => '/^1[3-9]\d{9}$/'
]));

$group = $validation->validate([
    'phone' => '123456789',
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // phone匹配失败
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\StringLength;

$validation = new Validation();
$validation->add('name', new StringLength([
    StringLength::OPT_MAX => 10,
]));

$group = $validation->validate([
    'name' => 'adminadminadmin',
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // name长度不能超过10个字符
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\StringLength;

$validation = new Validation();
$validation->add('name', new StringLength([
    StringLength::OPT_MIN => 5,
    StringLength::OPT_MAX => 10,
    StringLength::OPT_MESSAGE_MAX => ':field最大长度为:length',
]));

$group = $validation->validate([
    'name' => 'adminadminadmin',
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // name最大长度为10
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\StringLength;

$validation = new Validation();
$validation->add(['name', 'username'], new StringLength([
    StringLength::OPT_MIN => 5,
    StringLength::OPT_MAX => [
        'name' => 10,
        'username' => 20,
    ],
    StringLength::OPT_MESSAGE_MIN => [
        'name' => '姓名最小长度为:length',
        'username' => '用户名最小长度为:length',
    ],
    StringLength::OPT_MESSAGE_MAX =>':field最大长度为:length',
]));

$group = $validation->validate([
    'name' => 'adminadminadmin',
    'username' => 'adm',
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // name最大长度为10
                        // 用户名最小长度为5
}

class Model
{
    /**
     * 功能:验证唯一值(默认)
     * 修改日期:2019/8/27
     *
     * @param array $data 数据
     * @param array $filed 字段
     * @return bool
     */
    public function isUniqueness($data, $filed)
    {
        return false;
    }

    /**
     * 功能:验证唯一值(需指定)
     * 修改日期:2019/8/27
     *
     * @param array $data 数据
     * @param array $filed 字段
     * @return bool
     */
    public function isUniqueness2($data, $filed)
    {
        return false;
    }
}



// 使用
use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Uniqueness;

$validation = new Validation();
$validation->add('name', new Uniqueness([
    'model' => new Model(),
]));

$group = $validation->validate([
    'name' => 'admin'
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // name已存在
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\Uniqueness;

$validation = new Validation();
$validation->add(['name', 'status'], new Uniqueness([
    Uniqueness::OPT_MODEL => new Model(),
    Uniqueness::OPT_METHOD => 'isUniqueness2', // 非必须,当Model中无isUniqueness方法时,需指定方法
    Uniqueness::OPT_ATTRIBUTE => [
        'name' => 'username'
    ],
    Uniqueness::OPT_CONVERT => function ($data) {
        if (isset($data['name'])) {
            $data['name'] = ucfirst($data['name']);
        }
        return $data;
    }
]));

$group = $validation->validate([
    'name' => 'admin',
    'status' => 0,
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // name,status已存在
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\File;

$validation = new Validation();
$validation->add('image', new File([
    File::OPT_ALLOW_TYPES => ['image/jpeg'],
]));

$group = $validation->validate($_FILES);

foreach ($group as $msg) {
    echo $msg, '<br>'; // image的文件类型必须为image/jpeg
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\File;

$validation = new Validation();
$validation->add('image', new File([
    File::OPT_MIN_SIZE => '3M',
    File::OPT_INCLUDE_MIN_SIZE => false,
    File::OPT_MESSAGE_MIN_SIZE => '图片最小为:size',
]));

$group = $validation->validate($_FILES);

foreach ($group as $msg) {
    echo $msg, '<br>'; // 图片最小为3M
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\File;

$validation = new Validation();
$validation->add('image', new File([
    File::OPT_MAX_SIZE => '100KB',
]));

$group = $validation->validate($_FILES);

foreach ($group as $msg) {
    echo $msg, '<br>'; // image的文件大小不能大于100KB
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\File;

$validation = new Validation();
$validation->add('image', new File([
    File::OPT_MIN_RESOLUTION => '953x592',
]));

$group = $validation->validate($_FILES);

foreach ($group as $msg) {
    echo $msg, '<br>'; // image的图像分辨率不能小于953x592
}

use Snow\Validation\Validation;
use Snow\Validation\Validation\Validator\InclusionIn;

$validation = new Validation();
$validation->add('ip', new Ip());

$group = $validation->validate([
    'ip' => '3..115.201.2'
]);

foreach ($group as $msg) {
    echo $msg, PHP_EOL; // ip必须是有效的IP地址
}