数据校验

EasySwoole提供了基础的数据校验。

  1. $data = array(
  2. "a"=>1,
  3. "b"=>array(
  4. "age"=>2,
  5. "b2"=>null
  6. ),
  7. "c"=>array(
  8. "age"=>3,
  9. "b2"=>"asas"
  10. ),
  11. "URL"=>'http://www.baidu.com',
  12. "regex"=>"121sssss212"
  13. );
  14. $validate = new \Core\Utility\Validate\Validate();
  15. $validate->addField("a")->withRule(\Core\Utility\Validate\Rule::REQUIRED)
  16. ->withMsg("a字段不能为空")->withRule(\Core\Utility\Validate\Rule::BETWEEN,-1,3)
  17. ->withMsg("区间范围错误");
  18. $validate->addField("b.b2")->withRule(\Core\Utility\Validate\Rule::REQUIRED)
  19. ->withMsg('b字段不能为空')->withMsg('b2的全局错误信息')
  20. ->withRule(\Core\Utility\Validate\Rule::ALPHA);
  21. $validate->addField("*.age")->withRule(\Core\Utility\Validate\Rule::NUMERIC)
  22. ->withRule(\Core\Utility\Validate\Rule::BETWEEN,1,2);
  23. $validate->addField("URL")->withRule(\Core\Utility\Validate\Rule::ACTIVE_URL);
  24. $validate->addField("regex")
  25. ->withRule(\Core\Utility\Validate\Rule::REGEX,"/^\d*$/")->withMsg('不符合正则');
  26. $result = $validate->validate($data);
  27. var_dump($result->hasError());
  28. var_dump($result->all());
  29. var_dump($result->getError("b.b2")->first());
  30. var_dump($result->getError("not exist")->first());

支持规则列表:

  1. /*
  2. \Core\Utility\Validate\Rule
  3. */
  4. class Rule
  5. {
  6. const ACTIVE_URL = 'ACTIVE_URL';
  7. const ALPHA = 'ALPHA';
  8. const BETWEEN = 'BETWEEN';
  9. const BOOLEAN = 'BOOLEAN';
  10. const DATE = 'DATE';
  11. const DATE_AFTER = 'DATE_AFTER';
  12. const DATE_BEFORE = 'DATE_BEFORE';
  13. const DIFFERENT = 'DIFFERENT';
  14. const FLOAT = 'FLOAT';
  15. const IN = 'IN';
  16. const INTEGER = 'INTEGER';
  17. const IP = 'IP';
  18. const ARRAY_ = 'ARRAY_';
  19. const LEN = 'LEN';
  20. const NOT_IN = 'NOT_IN';
  21. const NUMERIC = 'NUMERIC';
  22. const MAX = 'MAX';
  23. const MAX_LEN = 'MAX_LEN';
  24. const MIN = 'MIN';
  25. const MIN_LEN = 'MIN_LEN';
  26. const OPTIONAL = 'OPTIONAL';
  27. const REGEX = 'REGEX';
  28. const REQUIRED = 'REQUIRED';
  29. const SAME = 'SAME';
  30. const TIMESTAMP = 'TIMESTAMP';
  31. const URL = 'URL';
  32. }

具体规则的验证原理,在\Core\Utility\Validate\Func中。