PHP Class Validator using php 8.0 attributes.
Caution
This package no longer maintained, use symfony/validator instead.
Using Composer:
composer require "hsnfirdaus/class-validator"Example Usage:
<?php
declare(strict_types=1);
namespace MyApp\Contract\User;
use Hsnfirdaus\ClassValidator\Attribute\IsEnum;
use Hsnfirdaus\ClassValidator\Attribute\IsNotEmpty;
use Hsnfirdaus\ClassValidator\Attribute\IsOptional;
use Hsnfirdaus\ClassValidator\Validator;
use MyApp\Entity\Enum\UserRole;
use MyApp\Entity\Enum\UserType;
class AddUserContract
{
#[Name(name: 'User Type')]
#[IsNotEmpty]
#[IsEnum(enum: UserType::class)]
public string $type = 'Can\'t be empty';
#[IsNotEmpty]
#[IsEnum(enum: UserRole::class)]
public string $role = 'ValidEnumValue';
#[IsOptional]
public string $identifier;
public function validate()
{
Validator::validate($this);
}
}Then call validate method, it will throw exception if found an error. Currently this package only support property attribute.
Available attributes (see src/Attribute folder):
IsEmail(): Email validation (using phpfilter_varfunction).IsEnum(enum: ExampleEnum::class): Enum validation from string value.IsInteger(): Integer validation (using phpis_intfunction).IsNotEmpty(): Validate trimmed value is not empty string or null.IsNumeric(length?: number, minLength?: number, maxLength?: number): Validate numeric string (using phpis_numericfunction).IsOptional(): Attribute to mark the property is optional, allow to be not defined.IsString(length?: number, minLength?: number, maxLength?: number): Validate string length.Name(name: string): Set error message field name (optional, default will be the property name).ValidateArrayClass(type: string): Nested validate array of class.ValidateClass(): Nested validate class.
Currently only English and Indonesian error message will thrown (see locale). Default will be English.
To change locale you can use and setLang method in your root or boot project:
<?php
declare(strict_types=1);
require __DIR__.'/vendor/autoload.php';
use Hsnfirdaus\ClassValidator\Validator;
Validator::setLang('id');
// Then you can call Validator::validate methodOr, you can use your own locale with setLangDir method. For example, create your locale file in __DIR__.'/locale/kr.php, then you can use:
Validator::setLangDir(__DIR__.'/locale');
Validator::setLang('kr');