Micro Dream Form Validate

website·Indexed 31 days ago

https://v.itwmw.com/

A lightweight, flexible, and high-performance PHP form validation library. It supports scenario-based management, custom validation rules, type casting, and data processing. The library includes a fluent Collection wrapper and integrates with frameworks like Symfony, Laravel, and ThinkPHP, with available plugins for routing middleware automation.

Tokens
41.4K
Snippets
289
Records
345
Agent score
47%

What's inside Micro Dream Form Validate

  1. Overview of wm-validate core capabilities

    The wm-validate library provides several key features for managing complex validation logic:

    • Rule Management: Includes 40+ built-in rules for data types, formats, and file uploads, with support for custom and private rules.
    • Validation Scenes: Allows defining multiple field combinations for different business contexts (e.g., login vs. registration) to reduce code duplication.
    • Error Messages: Supports custom error message templates, multi-language support, and field aliases for user-friendly feedback.
  2. Micro Dream Form Validate core capabilities

    The library provides the following core features for PHP form validation:

    • Rules Management: Over 40 built-in rules for data types, formats, and file uploads. Supports custom and private rules with parameter parsers.
    • Validation Scenes: Ability to define field combinations once and switch between them (e.g., login, registration, password change) to reduce code duplication.
    • Error Messages: Support for custom message templates, multi-language messages, field aliases, and variable injection in prompts.
  3. Customize validation rules for a specific scene

    To override or extend rules for a specific scenario, define a method named scene followed by the capitalized name of the scenario (e.g., sceneEdit). This method receives an instance of Itwmw\Validate\Support\ValidateScene, allowing you to modify rules using methods like only(), append(), and remove(). Note: Scene names cannot be called using underscore-converted hump writing.
    protected function sceneEdit($scene)
    {
        return $scene->only(['id','content','title'])
            ->append('id', "max")
            ->remove("content", 'between')
            ->remove('title', null)
            ->append('title', 'required|between|alpha');
    }
  4. Implement a custom Processor class

    Create a custom processor by implementing the Itwmw\Validate\Support\Concerns\ProcessorInterface. The handle method receives the value, attribute name, and original data. You can also use the constructor to pass configuration parameters to the processor class.
    use Itwmw\Validate\Support\Concerns\ProcessorInterface;
    
    class RemoveScriptProcessor implements ProcessorInterface
    {
        protected array $allowTags;
    
        public function __construct(string $allowTags = '')
        {
            $this->allowTags = explode(',', $allowTags);
        }
    
        public function handle($value, string $attribute, array $originalData)
        {
            $value = preg_replace('/<script.*?>.*?<\/script>/si', '', $value);
            return strip_tags($value, $this->allowTags);
        }
    }
    
    // Usage in Validate class
    protected $postprocessor = [
        'name' => RemoveScriptProcessor::class,
    ];
  5. Pass parameters to custom validation rules

    Custom rules can accept parameters (e.g., max:100). These parameters are passed in order to the rule class constructor. The rule class must extend BaseRule and implement the passes($attribute, $value) method.
    class Length extends BaseRule
    {
        protected $message = 'The length of :attribute is invalid';
        protected $size;
    
        public function __construct(int $size)
        {
            $this->size = $size;
        }
    
        public function passes($attribute, $value): bool
        {
            return strlen($value) === $this->size;
        }
    }
  6. Create a custom validator class

    To define reusable validation logic for specific scenarios or forms, create a class that extends Itwmw\Validate\Validate. Define the rules and messages as protected properties. Use the check() method to validate data. Validated data is returned as an array upon success, or a ValidateException is thrown on failure.
    class LoginValidate extends Validate
    {
        protected $rule = [
            'user' => 'required|email',
            'pass' => 'required|digits_between:6,16',
        ];
        
        protected $message = [
            'user.required'       => '请输入用户名',
            'user.email'          => '用户名格式错误',
            'pass.required'       => '请输入密码',
            'pass.digits_between' => '密码长度为6~16位',
        ];
    }
    
    // Usage
    $data = ['user' => '123@qq.com', 'pass' => '123456'];
    $validate = new LoginValidate();
    $result = $validate->check($data);
  7. Reuse and associate validation scenes

    Use the 'next' keyword within the $scene array to either reuse another scene's requirements or chain multiple scenes together. If a scene contains both specific fields and a 'next' key, the validator will verify the current fields first and then proceed to the next specified scene.
    protected $scene = [
        // Scene Reuse: 'save' uses the same fields as 'edit'
        'edit' => ['id','content','title'],
        'save' => ['next' => 'edit'],
    
        // Scene Association: 'register' validates its fields, then 'checkUserInfo'
        'register'      => ['username', 'password', 'mobile', 'next' => 'checkUserInfo'],
        'checkUserInfo' => ['name', 'age']
    ];
  8. Implement a custom validation event class

    To create a custom validation event handler, the class must inherit from Itwmw\Validate\Support\Event\ValidateEventAbstract. The class can implement beforeValidate() and afterValidate() methods. If these methods return false, the validator will use the value of the $message property as the error message. If a string is returned, it is treated as a message key (e.g., user.required) and a ValidateException is thrown.
    use Itwmw\Validate\Support\Event\ValidateEventAbstract;
    
    class CheckPermission extends ValidateEventAbstract
    {
        public $sceneName; // Current scene name
        public $data;      // Values before or after validation
        public $message;    // Error message used if returning false
    
        public function beforeValidate(): bool
        {
            // Logic before validation
            return true;
        }
    
        public function afterValidate(): bool
        {
            // Logic after validation
            return true;
        }
    }
  9. Use the 'and' rule for strict group validation

    While the or rule considers a group satisfied if any single rule within it passes, the AndRule requires all rules within the group to pass. This is useful for creating complex validation logic where a field must match a specific set of criteria (e.g., a specific language and length).
    class User extends Validate
    {
        public function __construct()
        {
            $this->group = [
                'chinese_name' => new AndRule(['chs', 'min:2', 'max:4']),
                'english_name' => new AndRule(['alpha', 'min:4', 'max:20']),
            ];
        }
    
        protected $rule = [
            'name' => 'required|string|or:chinese_name,english_name',
        ];
    }
  10. Implement a Presence Verifier for Exists and Unique rules

    When using Exists or Unique validation rules, a presence verifier is required to interact with the database. You must implement the Itwmw\Validation\Support\Interfaces\PresenceVerifierInterface interface and register the implementation via ValidateConfig.
    class PresenceVerifier implements PresenceVerifierInterface {}
    
    ValidateConfig::instance()->setPresenceVerifier(new PresenceVerifier());
  11. Integrate RuleParamsParser into a Validator class

    To enable dynamic data fetching within rule definitions, include the RuleParamsParser trait in your validator class that extends Validate.
    use Itwmw\Validate\Support\Traits\RuleParamsParser;
    use Itwmw\Validate\Validate;
    
    class Validator extends Validate
    {
        use RuleParamsParser;
    }