CallUserRuleTest.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace EasySwoole\Validate\tests;
  3. use EasySwoole\Validate\Functions\AbstractValidateFunction;
  4. use EasySwoole\Validate\Validate;
  5. class CustomValidator extends AbstractValidateFunction
  6. {
  7. /**
  8. * 返回当前校验规则的名字
  9. */
  10. public function name(): string
  11. {
  12. return 'mobile';
  13. }
  14. /**
  15. * 失败里面做异常
  16. * @param $itemData
  17. * @param $arg
  18. * @param $column
  19. */
  20. public function validate($itemData, $arg, $column, Validate $validate): bool
  21. {
  22. $regular = '/^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$/';
  23. if (!preg_match($regular, $itemData)) {
  24. return false;
  25. }
  26. return true;
  27. }
  28. }
  29. /**
  30. * @internal
  31. */
  32. class CallUserRuleTest extends BaseTestCase
  33. {
  34. // 合法断言
  35. public function testValidCase()
  36. {
  37. $this->freeValidate();
  38. $this->validate->addFunction(new CustomValidator());
  39. $this->validate->addColumn('mobile')->callUserRule(new CustomValidator(), '手机号验证未通过');
  40. $validateResult = $this->validate->validate([
  41. 'mobile' => '13312345678',
  42. ]);
  43. $this->assertTrue($validateResult);
  44. }
  45. // 默认错误信息断言
  46. public function testDefaultErrorMsgCase()
  47. {
  48. // 手机号验证不通过
  49. $this->freeValidate();
  50. $this->validate->addFunction(new CustomValidator());
  51. $this->validate->addColumn('mobile')->callUserRule(new CustomValidator(), '手机号验证未通过');
  52. $validateResult = $this->validate->validate(['mobile' => '12312345678']);
  53. $this->assertFalse($validateResult);
  54. $this->assertEquals('手机号验证未通过', $this->validate->getError()->__toString());
  55. }
  56. // 自定义错误信息断言
  57. public function testCustomErrorMsgCase()
  58. {
  59. // 日期相等
  60. $this->freeValidate();
  61. $this->validate->addFunction(new CustomValidator());
  62. $this->validate->addColumn('mobile')->callUserRule(new CustomValidator(), '手机号格式错误');
  63. $validateResult = $this->validate->validate(['mobile' => '12312345678']);
  64. $this->assertFalse($validateResult);
  65. $this->assertEquals('手机号格式错误', $this->validate->getError()->__toString());
  66. }
  67. }