Pvalidate: Object Validation

Usage

<?php

require_once "vendor/autoload.php";

use Webhkp\Pvalidate\Rules\Custom;
use Webhkp\Pvalidate\Rules\Regex;
use Webhkp\Pvalidate\Rules\ValidationRule;
use Webhkp\Pvalidate\Validator;
use Webhkp\Pvalidate\Rules\Required;
use Webhkp\Pvalidate\Rules\Range;
use Webhkp\Pvalidate\Rules\Allow;
use Webhkp\Pvalidate\Rules\Disallow;

class MyClass {
    public function __construct(
        #[Required]
        public string $name
    ) {

    }

    #[Required]
    public string $address;

    #[Required]
    public string $description;

    #[Range(min: 50, max: 60)]
    const AGE = 40;

    #[Range(min: 50)]
    public int $prop1 = 40;

    #[Range(max: 10)]
    #[Disallow([1, 2, 3, 40])]
    public int $prop2 = 40;

    #[Range()]
    #[Allow([1, 2, 3, 40])]
    public int $prop3 = 40;

    #[Required]
    public array $myArr = [];

    #[Regex('/[A-Z0-9]+/')]
    public string $regexTestField = 'AB23DE';

    #[MyCustomPasswordRule(100)]
    public string $password = 'mysimplepass';
}


// Usage
$myObj = new MyClass("Test ABC");
$myObj->description = "Some desc string for testing";

$validationResponse = Validator::validate($myObj);

var_dump($validationResponse->isValid());
var_dump($validationResponse->getErrors());
var_dump($validationResponse->getResult());

var_dump($validationResponse->getMessages());



// Check required validation
// $requiredValidation = new Required();
try {
    $requiredValidationResult = (new Required)->parse(null);

    var_dump($requiredValidationResult->isValid());
    var_dump($requiredValidationResult->getErrors());
} catch (\Exception $e) {
    var_dump($e);
}


// Check password validation
$passwordRule = new MyCustomPasswordRule(10);
$passValidationResult = $passwordRule->parse('simplepass');

var_dump($passValidationResult->isValid());
var_dump($passValidationResult->getErrors());

// Regex validation
$regexRule = new Regex('/^[A-Z0-9]{3}.*/');
$regexResult = $regexRule->safeParse('D2ab');
var_dump($regexResult->isValid());
var_dump($regexResult->getErrors());

Output:

bool(false)

array(3) {
  ["address"]=>
  array(1) {
    ["required"]=>
    string(19) "address is Required"
  }
  ["prop1"]=>
  array(1) {
    ["min"]=>
    string(42) "prop1 should be larger than or equal to 50"
  }
  ["prop2"]=>
  array(1) {
    ["max"]=>
    string(43) "prop2 should be smaller than or equal to 10"
  }
}

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.