验证规则 notEmpty 和 requirePresence

Validation rules notEmpty and requirePresence

我想知道各种验证规则如何相互作用以及它们如何叠加。

我认为最简单的方法是举几个例子。

假设我们要为博客提交 Post。因此,我们将在 PostsTable.

中进行验证
->notEmpty('title')
->requirePresence('title')
->add('title', 'length', [
    'rule' => ['minLength', 5],
    'message' => 'Must be longer than 5 characers'
]);

->notEmpty('download_speed')
->add('download_speed', 'rule', ['rule' => 'numeric'])
->requirePresence('download_speed')

所以在这个例子中,notEmpty()requirePresence() 规则是否真的需要,因为 minLength 将强制存在而不是空的,因为显然空字符串小于 5字符?

与第二个示例类似,空值不会是数字,因此规则会反过来强制它存在。

requirePresence 是唯一在给定字段不存在时触发的 built-in 规则,所有其他规则仅在字段实际存在的情况下应用,即 [=如果 title 字段不存在,11=] 将不会触发。因此,如果您需要一个字段存在并因此得到验证,那么您将需要 requirePresence 规则。

另外 minLength 会被空格满足,所以如果你不认为 5 个空格是有效的标题,那么你也不能放弃 notEmpty 规则(尽管你可能想交换两个, notEmptyminLength 对于自定义规则而不是 trim 是标题,这样 4 个空格后跟一个字符就不会通过验证,或者你可以 trim 你实体中的数据)。

您的示例中可能不需要的唯一规则是 download_speed 字段的 notEmpty 规则,因为正如您已经想到的那样,空值不是有效数字。

// Check:  != ''
    ->notEmpty('title')

// Check:  isset()
    ->requirePresence('title')

// Check:  5 characters at least but can be white spaces 
    ->add('title', 'length', [
         'rule' => ['minLength', 5],
          'message' => 'Must be at least 5 characters in length'
     ]);

// Check:  5 characters without white spaces behind or after
     ->add('title', 'custom', [
         'rule' => function ($currentData) {                        
              $realLenght = strlen(trim($currentData));  
               if ($realLenght >= 5 ) {return true;}
               return false;                  
          },                                    
         'message' => 'Must be at least 5 characters in length. Avoid unnecessary white spaces''
    ]);