进囗 發表於 2019-5-15 19:43:00

PHP验证器类Validator

<blockquote>
<p>Particle\Validator是一个小巧优雅的实用的PHP验证类库,提供了一个非常简洁的API。它无需依赖其他组件,提供友好的文档,并且有利于扩展。</p>
</blockquote>
<h2 id="安装">安装</h2>
<pre><code> composer require particle/validator
</code></pre>
<h2 id="使用">使用</h2>
<p>在使用之前请确保在项目中引入了 vendor/autoload.php 文件</p>
<pre><code>Code:
        1. &lt;?php
        2. use Particle\Validator\Validator;
        3. require './vendor/autoload.php';
        4. $v = new Validator;
        5. $v-&gt;required('first_name')-&gt;lengthBetween(2, 30)-&gt;alpha();
        6. $v-&gt;required('last_name')-&gt;lengthBetween(2, 40)-&gt;alpha();
        7. $data = [
        8. 'first_name' =&gt; 'John',
        9. 'last_name' =&gt; 'Doe',
        10. ];
        11. $result = $v-&gt;validate($data);
        12. $result-&gt;isValid();// 返回bool(true or false)
</code></pre>
<blockquote>
<p>这个方法是内置的,主要用于检测某个key的值,如果希望检测的某个值可能为空,而希望验证通过,则我们可以设置该方法的第三个参数为true。(默认值为false 代表不能为空值)。其中 required 和 optional 的区别主要是如下 required 是验证的值必须存在;而 optional 是可选的,如果key存在,则验证,不存在,则不用验证。</p>
</blockquote>
<h3 id="数组方式验证">数组方式验证</h3>
<pre><code>Code:
        1. // 基本验证
        2. $values = [
        3. 'user' =&gt; [
        4. 'username' =&gt; 'bob',
        5. ]
        6. ];
        7. $v = new Validator;
        8. $v-&gt;required('user.username')-&gt;alpha();
        9. $result = $v-&gt;validate($values);
        10. $result-&gt;getValues() === $values; // bool(true)
</code></pre>
<h3 id="内置验证规则">内置验证规则\</h3>
<blockquote>
<p>allowEmpty(callable $callback)是否可以为空值,true则通过 反之亦然</p>
</blockquote>
<pre><code>Code:
        1. $v = new Validator;
        2. // 如果用户名存在,则验证通过
        3. $v-&gt;required('name')-&gt;allowEmpty(function (array $values) {
        4. return $values['namePresent'] === true;
        5. });
        6. $v-&gt;validate(['namePresent' =&gt; true, 'name' =&gt; 'John'])-&gt;isValid(); // true
        7. $v-&gt;validate(['namePresent' =&gt; true])-&gt;isValid(); // true
        8. $v-&gt;validate(['namePresent' =&gt; false])-&gt;isValid(); // false

</code></pre>
<p>alnum($allowWhitespace = false) 包含数字和字母,不允许空格,(a-z, A-Z, 0-9)<br>
alpha($allowWhitespace = false) 验证的字符包含 (a-z, A-Z),不允许空格。<br>
between($min, $max) 验证必须在一个数值范围,如(12, 34)。<br>
bool() 布尔Boolean值验证。<br>
callback(callable $callable) 回调验证。<br>
creditCard() 验证信用卡,验证之前必须先安装 composer require byrokrat/checkdigit。<br>
datetime($format = null) 验证日期。<br>
digits() 一串数字字符串验证,不包含小数。<br>
each(callable $callable) 遍历验证。<br>
email() 验证邮箱。<br>
equals($value) 验证是否相等。<br>
float()验证浮点数。<br>
greaterThan($value) 大于某个值。<br>
hash($hashAlgorithm, $allowUppercase = false) md5 sha1等验证。<br>
inArray(array $array, $strict = true) 验证是否属于数组范围内<br>
integer($strict = false) 整数验证。<br>
isArray() 数组验证。<br>
json()json格式字符串验证。<br>
length($length) 长度验证。<br>
lengthBetween($min, $max) 长度范围验证。<br>
lessThan($value) 小于验证。<br>
numeric() 验证浮点数和整数。<br>
phone($countryCode) 验证手机号,使用之前先安装 composer require giggsey/libphonenumber-for-php。<br>
regex($regex) 正则验证。<br>
required(callable $callback) 必须存在,不能为空。<br>
string() 字符串验证。<br>
url($schemes = []) 验证URL。<br>
uuid($version = Uuid::VALID_FORMAT) 验证UUID。<br>
提示信息覆盖<br>
Particle\Validator为默认规则提供了默认的消息提示,当然你也可以为验证规则设置特定的消息提示以覆盖默认值。</p>
<pre><code>Code:
        1. $v = new Validator;
        2. $v-&gt;required('first_name')-&gt;lengthBetween(0, 5);
        3. $v-&gt;required('last_name')-&gt;lengthBetween(0, 5);
        4. $v-&gt;overwriteDefaultMessages([
        5. LengthBetween::TOO_LONG =&gt; 'It\'s too long, that value'
        6. ]);
        7. $v-&gt;overwriteMessages([
        8. 'first_name' =&gt; [
        9. LengthBetween::TOO_LONG =&gt; 'First name is too long, mate'
        10. ]
        11. ]);
        12. $result = $v-&gt;validate([
        13. 'first_name' =&gt; 'this is too long',
        14. 'last_name' =&gt; 'this is also too long',
        15. ]);
        16. var_dump($result-&gt;getMessages());
</code></pre>
<h3 id="验证场景">验证场景</h3>
<blockquote>
<p>验证库一般都可以根据场景来使用不同的验证,比如插入数据和更新数据的区别</p>
</blockquote>
<pre><code>Code:
        1. $v = new Validator;
        2. // 定义一个插入时候的验证规则
        3. $v-&gt;context('insert', function(Validator $context) {
        4. $context-&gt;required('first_name')-&gt;lengthBetween(2, 30);
        5. });
        6. // 定义一个更新时候的验证规则
        7. $v-&gt;context('update', function(Validator $context) {
        8. $context-&gt;optional('first_name')-&gt;lengthBetween(2, 30);
        9. });
        10. $v-&gt;validate([], 'update')-&gt;isValid(); // bool(true)
        11. $v-&gt;validate([], 'insert')-&gt;isValid(); // bool(false), because first_name is required.
</code></pre>
<h3 id="在mvc架构中使用验证器">在MVC架构中使用验证器</h3>
<p>很多时候,我们的项目都是进行分层开发的,例如常见的MVC,则我们可以在分层项目中调用该验证类,示例如下:</p>
<pre><code>Code:
        1. use Particle\Validator\ValidationResult;
        2. use Particle\Validator\Validator;
        3. class MyEntity
        4. {
        5. protected $id;
        6. public function setId($id)
        7. {
        8. $this-&gt;id = $id;
        9. return $this;
        10. }
        11. public function validate() {
        12. $v = new Validator;
        13. $v-&gt;required('id')-&gt;integer();
        14. return new $v-&gt;validate($this-&gt;values());
        15. }
        16. protected function values()
        17. {
        18. return [
        19. 'id' =&gt; $this-&gt;id,
        20. ];
        21. }
        22. }
        23. // in a controller:
        24. $entity = new Entity();
        25. $entity-&gt;setId($this-&gt;getParam('id'));
        26. $result = $entity-&gt;validate();
        27. if (!$result-&gt;isValid()) {
        28. return $this-&gt;renderTemplate([
        29. 'messages' =&gt; $result-&gt;getMessages() // or maybe even just pass in $result.
        30. ]);
        31. }
</code></pre>
<p>http://validator.particle-php.com/en/latest/</p>


</div>
<div id="MySignature" role="contentinfo">
    这是来自https://www.cnblogs.com/qinsilandiao/的文章<br><br>
来源:https://www.cnblogs.com/qinsilandiao/p/10871617.html
頁: [1]
查看完整版本: PHP验证器类Validator