承接 nael_d/valida 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

nael_d/valida

Composer 安装命令:

composer require nael_d/valida

包简介

A comprehensive PHP validation library with support for 50+ validation rules, custom rules, profiles, and multi-language error messages

README 文档

README

Valida is a comprehensive PHP validation library featuring an extensive rule set of 50+ validation rules, support for custom validation rules, reusable validation profiles, multi-language error messages, and a fluent interface for building complex validation workflows.

Features

  • PHP Compatibility: Works with PHP >= 8.0.0 with modern type declarations and features.
  • 50+ Built-in Validation Rules: Extensive rule coverage including string, numeric, network, password security, and cross-field validations.
  • Custom Validation Rules: Register your own validation logic via callable functions for domain-specific requirements.
  • Validation Profiles: Define reusable validation configurations to avoid repetition across your application.
  • Multi-Language Support: Configure error messages in multiple languages with custom placeholders.
  • Rule Aliases: Create aliases for complex rule sets to simplify validation logic.
  • Cross-Field Validation: Validate fields based on the presence or absence of other fields (required_with, required_without, etc.).
  • Password Security: Built-in strong password validation and compromise detection via HaveIBeenPwned API.
  • Fluent Error Access: Simple error retrieval with field-indexed error messages.
  • International Character Support: Full support for Unicode, Arabic, and international characters in alpha validation.

Table of Contents

Installation

Valida is available via Composer. Install it in your project:

composer require nael_d/valida

You can also download Valida manually from the Releases page and require the src/ directory.

💡 For detailed version information and release notes, visit the CHANGELOG to review the development timeline and features.

Getting Started

Once installed, the Valida package is ready to use. The main entry point is the Valida class.

💡 The Valida class is available under the Valida namespace and should be instantiated with an optional configuration array.

use Valida\Valida;

// Load the configuration file
$config = require 'config.php';

// Create a Valida instance with configuration
$validator = new Valida($config, 'en');

// Define your data to validate
$data = [
  'username' => 'john_doe',
  'email' => 'john@example.com',
  'password' => 'SecurePass123!',
  'password_confirmation' => 'SecurePass123!',
];

// Define your validation rules
$rules = [
  'username' => 'required|username|min:3|max:20',
  'email' => 'required|email',
  'password' => 'required|min:8|strong_password|confirmed:password',
];

// Validate
if ($validator->check($data, $rules)) {
  echo "Validation passed!";
} else {
  $errors = $validator->getErrors();
  print_r($errors);
}

Configuration

The Valida class accepts an optional configuration array during instantiation. The configuration file (config.php) includes:

$config = [
  'default_response' => [
    'en' => 'The `:attribute` field contains invalid data.',
  ],
  'responses' => [
    'required' => [
      'en' => 'The `:attribute` field is required.',
    ],
    'email' => [
      'en' => 'The `:attribute` field must be a valid email address.',
    ],
    // ... more rules
  ],
  'aliases' => [
      // 'custom_alias' => 'rule_name',
  ],
  'profiles' => [
    'username_field'  => 'username',
    'email_field'     => 'required|email',
    'password_field'  => 'required|min:8|strong_password|confirmed:password|pwned',
  ],
  'custom_rules' => [
    // 'custom_rule' => function($value, $param, $allData) { ... },
  ],
];

Configuration Options:

  • default_response: Fallback error message when a rule has no custom response defined.
  • responses: Multi-language error messages for each validation rule.
  • aliases: Create shortcuts for your used rule name.
  • profiles: Reusable validation rule sets.
  • custom_rules: Register callable custom validation logic.

Properties

The Valida class maintains internal state with the following private properties:

  • $responses: array - Multi-language error messages for validation rules.
  • $lang: string - Current language for error messages (default: 'en').
  • $aliases: array - Aliases for validation rules.
  • $profiles: array - Reusable validation profiles.
  • $customRules: array - User-defined custom validation rules.
  • $errors: array - Validation errors from the last check() call.
  • $defaultResponse: array - Default error message per language.

Methods

Core Methods

__construct()

Initializes the Valida validator with optional configuration and language.

Parameters:

  • array $config: Optional. Configuration array with responses, aliases, profiles, and custom rules.
  • string $currentLang: Optional. Default language for error messages (default: 'en').

Usage:

$config = require 'config.php';
$validator = new Valida($config, 'en');

check()

Validates data against specified rules and returns whether all data passes validation.

Parameters:

  • array $data: The data to be validated.
  • array $rules: Validation rules mapped to field names.
  • array $customMessages: Optional. Custom error messages for specific rules.

Returns: bool - True if all validation passes, false otherwise.

Usage:

$data = [
  'email' => 'user@example.com',
  'age' => 25,
];

$rules = [
  'email' => 'required|email',
  'age' => 'required|integer|min:18',
];

$passes = $validator->check($data, $rules);

if (!$passes) {
  $errors = $validator->getErrors();
  foreach ($errors as $field => $messages) {
    foreach ($messages as $message) {
      echo "$field: $message\n";
    }
  }
}

Custom Error Messages

Override error messages per operation:

$customMessages = [
  'email.email' => 'Please provide a valid email address.',
  'age.min' => 'You must be at least 18 years old.',
];

$validator->check($data, $rules, $customMessages);

Error Retrieval

getErrors()

Retrieves all validation errors from the last check() operation.

Returns: array - Associative array where keys are field names and values are arrays of error messages.

Usage:

$validator->check($data, $rules);
$errors = $validator->getErrors();

// Output:
// [
//   'email' => ['The email field must be a valid email address.'],
//   'age' => ['The age field must be a positive integer.'],
// ]

Validation Rules

Valida provides a comprehensive set of built-in validation rules organized by category.

Core Validation

required

Checks if a value is present and not empty.

'username' => 'required',

boolean

Checks if a value is a valid boolean (true, false, 1, 0, '1', '0').

'is_active' => 'boolean',

String & Identity Validation

alpha

Checks if a value contains only letters (supports international characters including Arabic).

'first_name' => 'alpha',

alpha_num

Checks if a value contains only letters and numbers.

'product_code' => 'alpha_num',

username

Checks if a value matches username format (letters, numbers, dashes, underscores, dots).

'username' => 'username|min:3|max:20',

email

Checks if a value is a valid email address.

'email' => 'required|email',

url

Checks if a value is a valid URL.

'website' => 'url',

json

Checks if a value is a valid JSON string.

'metadata' => 'json',

date

Checks if a value is a valid date structure (uses strtotime()).

'birth_date' => 'date',

ascii

Checks if a value contains only standard ASCII characters.

'api_key' => 'ascii',

slug

Checks if a value is a valid URL slug (lowercase letters, numbers, hyphens, underscores).

'post_slug' => 'slug',

uuid

Checks if a value is a valid UUID (versions 1-5).

'unique_id' => 'uuid',

regex

Matches a value against a custom regular expression pattern.

'phone' => 'regex:/^[0-9\-\+]{10,}$/',

Numeric & Integer Validation

numeric

Checks if a value is a valid number.

'quantity' => 'numeric',

positive_numeric

Checks if a value is a positive number (>= 0).

'price' => 'positive_numeric',

negative_numeric

Checks if a value is a negative number (< 0).

'debt' => 'negative_numeric',

integer

Checks if a value is a valid integer.

'user_id' => 'integer',

positive_integer

Checks if a value is a positive integer (>= 0).

'count' => 'positive_integer',

negative_integer

Checks if a value is a negative integer (< 0).

'offset' => 'negative_integer',

gt (Greater Than)

Checks if a numeric value is strictly greater than a parameter.

'score' => 'gt:50',

gte (Greater Than or Equal)

Checks if a numeric value is greater than or equal to a parameter.

'age' => 'gte:18',

lt (Less Than)

Checks if a numeric value is strictly less than a parameter.

'discount' => 'lt:100',

lte (Less Than or Equal)

Checks if a numeric value is less than or equal to a parameter.

'percentage' => 'lte:100',

between

Checks if a numeric value or string length is between min and max values.

'age' => 'between:18,65',
'password' => 'between:8,255',

Constraints & Lists

min

Checks if a string length or numeric value meets a minimum requirement.

'password' => 'min:8',
'rating' => 'min:1',

max

Checks if a string length or numeric value meets a maximum requirement.

'bio' => 'max:500',
'salary' => 'max:1000000',

in

Checks if a value is one of the allowed options (comma-separated).

'status' => 'in:active,inactive,pending',
'role' => 'in:admin,user,moderator',

not_in

Checks if a value is NOT one of the disallowed options.

'username' => 'not_in:admin,root,support',

Cross-Field Validation

confirmed

Checks if a field's value matches its confirmation field (field_confirmation).

'password' => 'required|confirmed:password',
// Expects: password_confirmation field with matching value

required_with

Checks if a field is required when ANY of the specified fields are present (OR logic).

'mobile_confirmation_code' => 'required_with:mobile_number',

required_without

Checks if a field is required when ANY of the specified fields are NOT present (OR logic).

'mobile_number' => 'required_without:email_address',

required_with_all

Checks if a field is required when ALL specified fields are present (AND logic).

'billing_address' => 'required_with_all:first_name,last_name',

required_without_all

Checks if a field is required when ALL specified fields are NOT present (AND logic).

'alternative_contact' => 'required_without_all:phone,email',

Network Validation

ip

Checks if a value is a valid IP address (IPv4 or IPv6).

'server_ip' => 'ip',

ipv4

Checks if a value is a valid IPv4 address.

'ipv4_address' => 'ipv4',

ipv6

Checks if a value is a valid IPv6 address.

'ipv6_address' => 'ipv6',

Password Security Validation

strong_password

Checks if a password contains uppercase, lowercase, numbers, and special characters.

'password' => 'required|strong_password',

Requirements:

  • At least one uppercase letter (A-Z)
  • At least one lowercase letter (a-z)
  • At least one digit (0-9)
  • At least one special character (!@#$%^&*, etc.)

pwned

Checks if a password has appeared in known public data breaches via HaveIBeenPwned API.

'password' => 'required|strong_password|pwned',

⚠️ Note: This rule requires internet connectivity and uses the public HaveIBeenPwned API. It's safe: only a hash prefix is sent, never the full password.

Profiles & Aliases

Validation Profiles

Profiles are reusable validation rule sets that simplify complex validations:

'profiles' => [
    'username_field'  => 'username',
    'email_field'     => 'required|email',
    'password_field'  => 'required|min:8|strong_password|confirmed:password|pwned',
];

Usage:

$rules = [
    'username' => 'username_field',
    'email' => 'email_field',
    'password' => 'password_field',
];

$validator->check($data, $rules);

Rule Aliases

Aliases create shortcuts for commonly used rules:

'aliases' => [
    'strong_auth' => 'required|min:8|strong_password|pwned',
    'safe_name' => 'required|alpha|min:2|max:50',
];

Usage:

$rules = [
    'password' => 'strong_auth',
    'first_name' => 'safe_name',
];

Custom Rules

Register your own validation logic for domain-specific requirements:

$config = [
  'custom_rules' => [
    'valid_phone' => function($value, $param, $allData) {
      // Validate phone number format
      return preg_match('/^\+?[1-9]\d{1,14}$/', (string) $value) ? true : false;
    },
    'unique_email' => function($value, $param, $allData) {
      // Check if email exists in database
      $exists = checkEmailInDatabase($value);
      return !$exists;
    },
  ],
  'responses' => [
    'valid_phone' => [
      'en' => 'The `:attribute` field must be a valid phone number.',
    ],
    'unique_email' => [
      'en' => 'The `:attribute` email address is already registered.',
    ],
  ],
];

$validator = new Valida($config);

$rules = [
  'phone' => 'valid_phone',
  'email' => 'required|email|unique_email',
];

Custom Rule Callback Signature:

function($value, $param, $allData): bool
  • $value: The field value being validated
  • $param: Optional parameter (after colon in rule string)
  • $allData: Entire dataset for cross-field validation
  • Returns: bool - True if validation passes, false otherwise

💡 Important: Remember to add error responses for your custom rules in the responses configuration array. Follow the same pattern: 'rule_name' => ['en' => 'Error message...']. Without this, the default response will be used for validation failures.

Usage Examples

Basic Form Validation

use Valida\Valida;

$config = require 'config.php';
$validator = new Valida($config, 'en');

$data = [
  'username' => 'jane_doe',
  'email' => 'jane@example.com',
  'age' => 28,
];

$rules = [
  'username' => 'required|username|min:3',
  'email' => 'required|email',
  'age' => 'required|integer|between:18,120',
];

if ($validator->check($data, $rules)) {
  echo "All fields are valid!";
} else {
  $errors = $validator->getErrors();
  foreach ($errors as $field => $messages) {
    echo "$field: " . implode(', ', $messages) . "\n";
  }
}

Custom Error Messages

$customMessages = [
  'username.min' => 'Username must be at least 3 characters long.',
  'email.email' => 'Please enter a valid email address.',
  'age.between' => 'Age must be between 18 and 120 years old.',
];

$validator->check($data, $rules, $customMessages);

Password Confirmation

$data = [
  'password' => 'SecurePass123!',
  'password_confirmation' => 'SecurePass123!',
];

$rules = [
  'password' => 'required|min:8|strong_password|confirmed:password',
];

$validator->check($data, $rules);

Cross-Field Validation

$data = [
  'contact_method' => 'email',
  'email' => 'user@example.com',
  'phone' => '',
];

$rules = [
  'contact_method' => 'required|in:email,phone',
  'email' => 'required_with:contact_method',
  'phone' => 'required_without:email',
];

$validator->check($data, $rules);

Using Profiles

$config = [
  'profiles' => [
    'registration_form' => 'required|email|min:8|strong_password',
  ],
];

$validator = new Valida($config);

$rules = [
  'email' => 'registration_form',
  'password' => 'registration_form',
];

$validator->check($data, $rules);

Multi-Language Support

$config = [
  'responses' => [
    'required' => [
      'en' => 'The `:attribute` field is required.',
      'ar' => 'حقل `:attribute` مطلوب.',
      'fr' => 'Le champ `:attribute` est requis.',
    ],
  ],
];

// Validate in English
$validator = new Valida($config, 'en');
$validator->check($data, $rules);

// Validate in Arabic
$validator = new Valida($config, 'ar');
$validator->check($data, $rules);

Troubleshooting

"Rule not found": Ensure the rule name is spelled correctly and matches a built-in rule or registered custom rule.

// ❌ Wrong
'email' => 'emial', // Typo

// ✅ Correct
'email' => 'email',

"Custom rule not registered": Verify the custom rule exists in the custom_rules array.

$config = [
  'custom_rules' => [
    'my_rule' => function($value, $param, $allData) { return true; },
  ],
];

"Profile not found": Check that the profile name matches one defined in the configuration.

$config = [
  'profiles' => [
    'user_email' => 'required|email', // Profile name
  ],
];

$rules = [
  'email' => 'user_email', // Reference profile
];

"No errors but validation failed": Ensure you're checking the return value of check().

if (!$validator->check($data, $rules)) {
    $errors = $validator->getErrors(); // Get errors
}

"Pwned rule not working": Verify internet connectivity to HaveIBeenPwned API and check firewall/proxy settings.

Contributing

Valida is an open-source project and contributions are welcome! To contribute:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/your-feature)
  3. Commit your changes (git commit -am 'Add your feature')
  4. Push to the branch (git push origin feature/your-feature)
  5. Submit a Pull Request

Status

Valida has a well-tested released stable version in the main branch.

All ongoing development processes are located in the dev branch.

However, if you ever find any issue, don't hesitate to notify us by opening an issue describing and explaining the bug with a block of code.

For updates on the development process, please refer to the CHANGELOG in the dev branch.

License

This project is licensed under the MIT License. You are free to use, modify, and distribute this library under the terms of the MIT License. See the LICENSE file for details.

Made with ❤️ by Nael Dahman

统计信息

  • 总下载量: 0
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-06-14

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固