Giter Site home page Giter Site logo

inhere / php-validate Goto Github PK

View Code? Open in Web Editor NEW
255.0 13.0 33.0 634 KB

Lightweight and feature-rich PHP validation and filtering library. Support scene grouping, pre-filtering, array checking, custom validators, custom messages. 轻量且功能丰富的PHP验证、过滤库。支持场景分组,前置过滤,数组检查,自定义验证器,自定义消息。

Home Page: https://inhere.github.io/php-validate/

License: MIT License

PHP 99.78% HTML 0.22%
php-validation library tool validate validation-library validation filter

php-validate's Introduction

Hi Everyone 👋

inhere's github stats language


🚀💻 Technologies & Tools

Git GitHub IntelliJ PHP Java Go

My Organizations

Gookit Projects

ReadMe Card ReadMe Card
ReadMe Card ReadMe Card
ReadMe Card ReadMe Card

Contribuited Projects

ReadMe Card ReadMe Card

php-validate's People

Contributors

boobusy avatar consatan avatar dongasai avatar forainny avatar inhere avatar lscar avatar nelsonsun avatar zhangchenglin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-validate's Issues

自定义msg数组形式的无效果

这不知道是不是bug?

改用translates做了解决。

$v = \Inhere\Validate\Validation::make(data: [
    'title' => '',
    'name' => '',
], rules: array(
    ['title,name', 'required', 'msg' => [
        'tagId' => '标题不能为空。',
        'userId' => '姓名不能为空。',
    ]],
))->validate(
    stopOnError: !true
);
if ($v->isFail()) {
    var_dump($v->getErrors());
};

截屏2022-07-18 17 43 54

Improve eachValidator ?

Hi ! Thank you for this lib !

Is there a way to combine eachValidator with FieldValidation and filters ?
Perhaps with something like this :

$v = Inhere\Validate\FieldValidation::check(['array' => [
    [
        'string' => "   some words    ",
        'int' => "44",
    ], [
        'string' => "   some letters    ",
        'int' => "   456  ",
    ]
]], [
    ['array.*.int', 'each|required|int', 'filter' => 'int'],
    ['array.*.string', 'each|required|string', 'filter' => 'trim'],
]);

Bonus question : is there a way to get index/key in the errors array ? Currently we don't know which element is/are in error ?

  0 => array:2 [▼
    "name" => "array.*.int"
    "msg" => "array.*.int must be through the int verify"
  ]

二选一参数必选该用哪个验证器?

requiredIf
requiredUnless
requiredWith
requiredWithAll
requiredWithout
requiredWithoutAll

比如注册表单中的手机号和邮箱,选填其一。
该如何设置必填项?下面这种可以吗?

    ['email', 'requiredWithoutAll', ['phone']],
    ['email', "string:6,50", 'filter' => $filter],
    ['email', 'email'],

    ['phone', 'requiredWithoutAll', ['email']],
    ['phone', "fixedSize:11", 'filter' => $filter],
    ['phone', 'regexp', "{$regexp['phone']}"],

这种感觉提示结果不是预期想要的二选一提示。
只会提示最后一个被验证的字段提示

FieldValidation 的使用

希望在FieldValidation的使用中加入使用用例,方便查找与使用。
另外我还有一个问题,不知道是方法使用不当还是……,详情:
报错:

array(1) { [0]=> array(2) { ["name"]=> string(3) "age" ["msg"]=> string(52) "age must be an integer and value range {min} ~ {max}" } } 

运行代码:

        $data = [
            'id' => 1,
            'name' => '12345',
            'sex' => 0,
            'age' => 25,
            'love' => 'play'
        ];
        $v = v::check($data, [
            ['id', 'required'],
            ['name', 'required|string:5,10', 'msg' => '5~10位的字符串'],
            ['sex', 'required|enum:0,1'],
            ['age', 'requiredIf:sex,0|int']
        ]);
        if ($v->isFail()) {
            var_dump($v->getErrors());
        }

safe 字段有问题

例如save字段填写更新时间和修改时间,那当外部传入created_at和updated_at时,则会修改你本身填入save的字段里,从而改变你的创建时间与修改时间,这是一个很大的bug

如何验证中文

请问如何验证含有中文的字符串?是否有内置的验证器?
谢谢。

多维数组验证使用requiredIf时,无法使用

// src/Traits/ScopedValidatorsTrait.php
public function requiredIf(string $field, $fieldVal, string $anotherField, $values): ?bool
    {
       // 此处验证二维数组字段时,$anotherField可能时‘test.field1’, isset为false
        if (isset($this->data[$anotherField])) {
            $anotherVal = $this->data[$anotherField];

            // if (in_array($anotherVal, (array)$values, true)) {
            if (Helper::inArray($anotherVal, (array)$values)) {
                return $this->required($field, $fieldVal);
            }
        }

        return null;
    }

在swoft使用方式3来验证会出现报错。

PHP Fatal error: Uncaught Doctrine\Common\Annotations\AnnotationException: [Semantical Error] The annotation "@Date" in method Inhere\Validate\AbstractValidation::getMessage() was never imported. Did you maybe forget to add a "use" statement for this annotation? in /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php:54
Stack trace:
#0 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php(727): Doctrine\Common\Annotations\AnnotationException::semanticalError('The annotation ...')
#1 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php(663): Doctrine\Common\Annotations\DocParser->Annotation()
#2 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php(354): Doctrine\Common\Annotations\DocParser->Annotations()
#3 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php(286): Doctrine\ in /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php on line 54

PHP Fatal error: Uncaught Doctrine\Common\Annotations\AnnotationException: [Semantical Error] The annotation "@from" in method Inhere\Validate\AbstractValidation::requiredIf() was never imported. Did you maybe forget to add a "use" statement for this annotation? in /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php:54
Stack trace:
#0 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php(727): Doctrine\Common\Annotations\AnnotationException::semanticalError('The annotation ...')
#1 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php(663): Doctrine\Common\Annotations\DocParser->Annotation()
#2 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php(354): Doctrine\Common\Annotations\DocParser->Annotations()
#3 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php(286): Doctrine\ in /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php on line 54

PHP Fatal error: Uncaught Doctrine\Common\Annotations\AnnotationException: [Semantical Error] The annotation "@from" in method Inhere\Validate\AbstractValidation::requiredWithoutAll() was never imported. Did you maybe forget to add a "use" statement for this annotation? in /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php:54
Stack trace:
#0 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php(727): Doctrine\Common\Annotations\AnnotationException::semanticalError('The annotation ...')
#1 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php(663): Doctrine\Common\Annotations\DocParser->Annotation()
#2 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php(354): Doctrine\Common\Annotations\DocParser->Annotations()
#3 /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php(286): D in /usr/local/src/swoft-admin/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php on line 54

以上报错是因为注解的原因。
在php-validate/src/Utils/ErrorMessageTrait.php 的379行代码 @Date 有问题。目前我删除了@就不会报错
在php-validate/src/Utils/UserAndContextValidatorsTrait.php 的159、267行代码@from有问题。删除@就不会报错。
这个是否已经跟注解的关键字有冲突,希望能排查下

swoft使用验证,只能验证一次?变量没有被释放的问题

在php-validate/src/ValidationTrait.php 的161、265行代码有点问题,貌似变量未被释放,下次再来验证直接返回了。
场景:
我用postman来请求某个更新数据的接口,采用了方法3的方式进行验证。返回了缺少某个参数的错误,后面我修改了携带的参数,参数已经是完全正确的了,但是还是返回了相同的错误。追踪代码,发现在ValidationTrait.php 161行代码直接返回对象,不进行验证了。也就是$this->_validated为true了。这个如何解决呢?

为什么getErrors只抛出一条异常信息?

$v = \Inhere\Validate\Validation::check([
'title' => 'loggerSaveTime',
'age' => 2,
], [
['title', 'min', 30, 'msg' => '标题字数无效!'],
['age', 'int', 'min'=>4, 'max'=>16, 'msg' => '{attr} error!'],
]);
if ($v->isFail()) {
var_dump($v->getErrors());
//var_dump($v->firstError(!false));
}

getErrors只抛出一条异常信息:

截屏2022-07-17 12 07 06

字段的校验是通过empty判断存在时才进行validator吗?

现在有个场景,在参数约定remark字段为字符串,但自动化测试时remark给到了null,并没有触发string的校验,哪怕新写一个customStringValidator也不会触发:
image
image
这是service层参数打印:
image
参数校验是放controller上,说明入参字段为null时,并不会触发验证器
注:验证器继承的是:Inhere\Validate\FieldValidation

单字段多规则中,正则的值,能否用变量?

$MultipleRules = [
    ['captchaCode', 'fixedSize:4', 'msg' => $msg],
    ['username', 'required|string:3,15|regexp:{$regexp["username"]}', 'msg' => $msg],
//    ['username', 'required|string:3,15|regexp:^[a-zA-Z]\w{4,19}$', 'msg' => $msg],
    ['password', 'required|string:8,20|regexp:{$regexp["password"]}', 'msg' => $msg],
];

比如说 {$regexp["username"]}

不能这么写吗?

filter对each字段无效

代码:

$post = array(
    'prop' => [
        'money' => '22.4',
    ],
);
$rules = array(
    ['prop.money', 'float', 'min' => .1, 'filter' => 'float', 'msg' => '属性金额不能小于0.1元。'],
);
$v = \Inhere\Validate\Validation::make(
    $post,
    rules: $rules,
)->validate(stopOnError: !true);
if ($v->isFail()) {
    var_dump($v->getErrors());
    exit;
}
var_dump($post, $v->getSafeData()); exit;

输出:

array (size=1)
  'prop' => 
    array (size=1)
      'money' => string '22.4' (length=4)

是不是filter对each字段是无法处理的?

reuqire了toolkit/stdlib引起的坑

一般env这个函数都是框架会自己写一个的, composer自动加载有时候会把这个env先加载导致env函数优先使用toolkit/stdlib中的,太坑了。。。

支持场景规则配置到不同的方法

class UserRequest extends Validation
{
    // for scene 'create'
    public function rulesOnCreate(): array 
    {
        return [
            ['username,password', 'required', 'filter' => 'trim'],
            ['username,password', 'string'],
        ];
    }

    // for scene 'update'
    public function rulesOnUpdate(): array 
    {
        return [
            ['username,password, verifyCode', 'required', 'filter' => 'trim'],
            ['username,password', 'string'],
            ['verifyCode', 'string'],
        ];
    }
}

required时不能应用isempty

问题:
当一个字段在required验证时,不能使用isEmpty 自定义为空验证,导致某些required字段,验证不通过

期望值:
既然定义了isEmpty,那么在进行验证时就要用呀

字段比对的翻译,第二个参数错误

'eqField' => '{attr} value must be equals to {value0}',
'neqField' => '{attr} value cannot be equals to {value0}',
'ltField' => '{attr} value must be less than {value0}',
'lteField' => '{attr} value must be less than or equals to {value0}',
'gtField' => '{attr} value must be greater than {value0}',
'gteField' => '{attr} value must be greater than or equals to {value0}',

{value0} 应该是 {attr1}

因为 $translates 第二个参数名称没有被翻译

验证前的操作问题

我发现了你有onBeforeValidate这个功能,这证明你也发现了验证前可能需要一些神奇的操作,那么我就纳闷了,既然可以定义validation类,那么为什么不把这些个操作放在验证类内部执行呢?

ps:一顿分离猛如虎,一个耦合乱如麻呀!

readme中关于自定义规则的介绍有误

在方式1中提到自定义规则使用:

['title', 'customValidator', 'msg' => '{attr} error msg!' ], // 指定当前规则的消息

并且自定义了一个方法:

// 添加一个验证器。必须返回一个布尔值标明验证失败或成功
    protected function customValidator($title)
    {
        // some logic ...

        return true; // Or false;
    }

实际使用过程中,应用自定义规则名称不能使用"customValidator",而应该是"custom"。因为底层在执行验证时对方法名做了拼接。

【建议】不同场景使用的是规则名而非字段名。

类似这样的设计,

$rules = [
  'rule0'=>['field0', 'validator'],
  'rule1'=>['field1', 'validator'],
  'rule2'=>['field2', 'validator']
]

$scenes = [
  'scene0'=>['rule0', 'rule3'],
  'scene1'=>['rule1', 'rule3'],
]

如此,即可取代on的设计,在使用的时候更加灵活

为什么存在required验证的特殊分支?

https://github.com/inhere/php-validate/blob/master/src/ValidationTrait.php#L311

如上,safe的独立分支(标记安全的字段不需要其他验证),但是这个分支导致了 后续的after不可用

// required*系列字段检查 || 文件资源检查
if (self::isCheckRequired($validator) || self::isCheckFile($validator)) {
$result = $this->fieldValidate($field, $value, $validator, $args, $defMsg);
if (false === $result && $stopOnError) {
break;
}
continue;
}

如上required的分支是出于什么考虑?

返回的字段 命名规则被修改了, 希望修复.

配置文件中规则如下
注意,roomId是驼峰命名方式

'room/userQuit/v1' => [
            'validate' => ['roomId','required','msg' => '{attr} 必须!']
        ],

调用接口时,未传递这个参数
却变成了 room空格id
对接口使用人员造成了误导.

{
    "code": "4000",
    "msg": "参数错误:【room id 必须!】",
    "body": {}
}

自定义消息无效

$params = [];

$v = \Inhere\Validate\FieldValidation::check($params, [['owner', 'required', 'msg' => ['owner' => 'owner 缺失']]]);

if ($v->isFail()) {
    var_dump($v->firstError());
}

依然返回默认输出 string(28) "parameter owner is required!"

对数组子元素进行验证时验证结果返回异常

验证规则:

[
       ['goods_id', 'array', 'list', 'msg' => '商品id数组为空或不合法'],
       ['goods_id.*', 'integer', 'msg' => '商品分类id必须是一串数字']
]

验证的数据:

[
     "goods_id" => [
             1144181460261978556, 114418146, 1144
     ]
]

返回结果:商品分类id必须是一串数字

数组咋设置错误提示呢?

['users.*.id', 'each', 'required'],
['users.*.id', 'each', 'number', 'min' => 34],

例如这样的!
required number min 单独设置

[question] 请问如何使用afterValidate

我有一个场景,验证一个字段之后,需要验证更多的其他字段,例如我首先检验类型是否有值,并且是1到13之间的整数,通过验证之后,我在进行具体类型的很多字段类型验证,例如登陆的时候,如果是账号密码登录,就校验账号密码,如果是手机验证码登录,就校验手机号码和验证码。等等,有七八种登陆方式,每种登陆的方式娇艳的字段都不一样。所以就想使用afterValidate这个特性,但是不知道怎么用。

    public function onAfterValidate(Closure $cb)
    {
        $this->_afterHandler = $cb;
        return $this;
    }

    public function afterValidate(): void
    {
        if ($cb = $this->_afterHandler) {
            $cb($this);
        }
        // do something ...
    }

date验证器不支持 1970年以前

date验证器不支持 1970年以前,

$post = ['birthDay'=>'1960-09-21'];
$v = Valid::check($post,[
    ['birthDay', 'required'],
    ['birthDay', 'date'],
]);

就会返回 birth Day 不是有效日期。很奇怪。

暴露枚举值和inField没有提示语

'enum' => '{attr} must in ({value0})',
'notIn' => '{attr} cannot in ({value0})',

这个提示语等于暴露了允许的值。


inField 验证器没有提示语

public function inFieldValidator($val, string $anotherField): bool
{
if ($anotherField && $dict = $this->getByPath($anotherField)) {
return Validators::in($val, $dict);
}
return false;
}

requiredIf 规则实现有错误

requiredIf 的规则应该是: 另一个字段等于某值时,本字段必须; 如果不等于,则不应该检查本字段。

但是在我使用的 v2.4.11 版本中,无论另一个字段是否等于某值,本字段都必须。
原因是 UserAndContextValidatorsTrait.php 178行 判断另一字段不在匹配值中时直接返回了false。

假设改为return true让程序暂时正常进行

另外一个问题是,如果本字段不存在,在getSafeData()的时候会返回一个值为null的字段,我认为不应该返回这个字段。

验证器验证结果有误

TIM截图20190621202657
验证器结果有误,验证一个值是否为整形时,传入一个0提示: must be an integer!
不符合预期结果

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.