Custom validator

Common business default validators can be solved, but some business default validators can't be verified. In this case, users need to define the validators that meet their own business according to their own business needs.

Declaration validator

Declaring the validator is simple

  • Set a class to implement the Swoft\Validator\Contract\ValidatorInterface interface
  • Implement the validate method, which can define its own business validator logic
  • Use the @Validator annotation tag. This is a validator. This annotation uses exactly the same functionality as the previous one.

A validator is defined as follows, verifying that start time cannot be greater than end end time

 <?php declare(strict_types=1);

namespace App\Validator;

use Swoft\Validator\Annotation\Mapping\Validator;
use Swoft\Validator\Contract\ValidatorInterface;
use Swoft\Validator\Exception\ValidatorException;

/**
 * Class CustomerValidator
 *
 * @since 2.0
 *
 * @Validator(name="userValidator")
 */
class CustomerValidator implements ValidatorInterface
{
    /**
     * @param array $data
     * @param array $params
     *
     * @return array
     * @throws ValidatorException
     */
    public function validate(array $data, array $params): array
    {
        $start = $data['start'] ?? null;
        $end = $data['end'] ?? null;
        if ($start === null && $end === null) {
            throw new ValidatorException('Start time and end time cannot be empty');
        }
        if ($start > $end) {
            throw new ValidatorException('Start cannot be greater than the end time');
        }
        return $data;
    }
} 

Verification method details

 public function validate(array $data, array $params): array 
  • $data user input parameter, parsed into an array by the parser for
  • $params parameters passed to the validator, detailed in subsequent chapters

Validated to return the data after the validation process, if the validation fails, throw a Swoft\Validator\Exception\ValidatorException , and the rest is handled by the framework. If the value of the parameter needs to be modified in the validator, it can be modified directly. The modified value will get the new value.

/docs/2.x/en/validator/user-validator.html
progress-bar