You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP面向对象表单验证类扩展问题:新增规则失效及功能需求咨询

Fixing Your PHP OOP Form Validator

Got it, let's build a robust, extendable Validator class that handles all the rules you need—including fixing that broken max-length check, adding regex/number/email validation, and enforcing your custom password requirements.

Complete Validator Class Implementation

class Validator {
    private $data = [];
    private $errors = [];
    private $rules = [];

    // Initialize with form data
    public function __construct(array $data) {
        $this->data = $data;
    }

    // Add validation rules for a field (supports multiple rules at once)
    public function addRule(string $field, $rules): void {
        if (!isset($this->rules[$field])) {
            $this->rules[$field] = [];
        }

        // Handle both single rule string and array of rules
        if (is_string($rules)) {
            $rules = [$rules];
        }

        foreach ($rules as $rule) {
            $this->rules[$field][] = $this->parseRule($rule);
        }
    }

    // Parse rule string into rule name and parameters (e.g., "max_length:10" → ['max_length', [10]])
    private function parseRule(string $rule): array {
        if (str_contains($rule, ':')) {
            [$ruleName, $params] = explode(':', $rule, 2);
            $params = explode(',', $params);
            return [$ruleName, $params];
        }
        return [$rule, []];
    }

    // Run all validation rules
    public function validate(): bool {
        foreach ($this->rules as $field => $fieldRules) {
            $value = $this->data[$field] ?? '';

            foreach ($fieldRules as [$ruleName, $params]) {
                $method = "validate" . ucfirst($ruleName);
                if (method_exists($this, $method)) {
                    if (!$this->$method($value, $params, $field)) {
                        break; // Stop validating this field if one rule fails
                    }
                } else {
                    throw new Exception("Validation rule '$ruleName' does not exist.");
                }
            }
        }

        return empty($this->errors);
    }

    // Get validation errors
    public function getErrors(): array {
        return $this->errors;
    }

    // --- Validation Rule Methods ---
    private function validateRequired($value, array $params, string $field): bool {
        if (empty(trim($value))) {
            $this->errors[$field][] = "The $field field is required.";
            return false;
        }
        return true;
    }

    private function validateMax_length($value, array $params, string $field): bool {
        $maxLength = (int)$params[0];
        if (strlen(trim($value)) > $maxLength) {
            $this->errors[$field][] = "The $field field must be no longer than $maxLength characters.";
            return false;
        }
        return true;
    }

    private function validateMin_length($value, array $params, string $field): bool {
        $minLength = (int)$params[0];
        if (strlen(trim($value)) < $minLength) {
            $this->errors[$field][] = "The $field field must be at least $minLength characters.";
            return false;
        }
        return true;
    }

    private function validateNumber($value, array $params, string $field): bool {
        if (!is_numeric($value)) {
            $this->errors[$field][] = "The $field field must be a number.";
            return false;
        }
        return true;
    }

    private function validateEmail($value, array $params, string $field): bool {
        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
            $this->errors[$field][] = "The $field field must be a valid email address.";
            return false;
        }
        return true;
    }

    // Custom password rule: 5-8 chars, at least one uppercase and one lowercase letter
    private function validatePassword_strength($value, array $params, string $field): bool {
        $pattern = '/^(?=.*[a-z])(?=.*[A-Z]).{5,8}$/';
        if (!preg_match($pattern, $value)) {
            $this->errors[$field][] = "The $field field must be 5-8 characters long, and include at least one uppercase and one lowercase letter.";
            return false;
        }
        return true;
    }

    // Add custom regex validation
    private function validateRegex($value, array $params, string $field): bool {
        $pattern = $params[0];
        if (!preg_match($pattern, $value)) {
            $errorMsg = $params[1] ?? "The $field field is invalid.";
            $this->errors[$field][] = $errorMsg;
            return false;
        }
        return true;
    }
}

How to Use the Validator

Here's an example of integrating it with your form data:

// Sample form data (replace with $_POST or $_GET)
$formData = [
    'username' => 'john_doe',
    'email' => 'john@example.com',
    'age' => '25',
    'password' => 'Pass123',
    'bio' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
];

// Initialize validator
$validator = new Validator($formData);

// Add rules for each field
$validator->addRule('username', ['required', 'max_length:20']);
$validator->addRule('email', ['required', 'email']);
$validator->addRule('age', ['required', 'number']);
$validator->addRule('password', ['required', 'password_strength']);
$validator->addRule('bio', 'max_length:100'); // Single rule as string

// Run validation
if (!$validator->validate()) {
    // Display errors
    foreach ($validator->getErrors() as $field => $errors) {
        echo "<strong>$field:</strong><br>";
        foreach ($errors as $error) {
            echo "- $error<br>";
        }
    }
} else {
    echo "All fields are valid!";
}

Key Fixes & Features Explained

  • Fixed Max-Length Issue: The parseRule method correctly splits rules like max_length:10 into the rule name and parameter, so the validator knows exactly what length to check against.
  • Extensible Rules: You can add new validation methods anytime by creating a new validate[RuleName] method (e.g., validatePhone for phone number checks).
  • Password Strength: The password_strength rule uses a regex that enforces:
    • 5-8 characters total
    • At least one lowercase letter ((?=.*[a-z]))
    • At least one uppercase letter ((?=.*[A-Z]))
  • Regex Flexibility: The regex rule lets you pass custom patterns and error messages, e.g.:
    $validator->addRule('phone', 'regex:/^\+?[0-9]{10,15}$/|The phone number is invalid.');
    
  • Clean Error Handling: Errors are grouped by field, making it easy to display them next to the corresponding form inputs.

内容的提问来源于stack exchange,提问作者Muhammad Ilyas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:01:46