Pvalidate: Basic Validation

To validate an object of a class, we first need to add the validation rules to the class properties, as attributes. Let’s see how perform a basic validation-

Import Validation Rules

Rules are in the namespace Webhkp\Pvalidate\Rules. So, import the validation rules you need-

use Webhkp\Pvalidate\Rules\Regex;
use Webhkp\Pvalidate\Rules\Required;
use Webhkp\Pvalidate\Rules\Range;
use Webhkp\Pvalidate\Rules\Allow;
use Webhkp\Pvalidate\Rules\Disallow;

Add Validation Rule to Property

We can add the rules as an attribute to the property. Multiple attributes can be added to a property for applying multiple validation rules to the property.

The address and description properties are required and must be provided.
The AGE constant is defined but note that constants should not be validated using property validation rules.
prop1 must be an integer greater than or equal to 50.
prop2 must be an integer less than or equal to 10 and must not be one of the values 1, 2, 3, or 40.
prop3 must be an integer and one of the allowed values: 1, 2, 3, or 40.
myArr is a required array property.
regexTestField must match the regex pattern /^[A-Z0-9]+/.
class MyClass {

    #[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 = 'aBCDE398';
}

Add Validation Rule while Property Promotion

We can add the validation rules while defining the field in the construction declaration, in property promotion. Here is an example-

The name property is a required field here and needs to be set while creating the object.
<?php

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

    }
}

Import the Validator

Import the validator from Webhkp\Pvalidate\Validator

use Webhkp\Pvalidate\Validator;

Validation Process

Use the static method Validator::validate for the validation. Then we can call the following methods to get the results and errors-

isValid() : check if the result is valid or not. If any of the properties does not satisfy the assigned rule, then the whole result will be invalid.
getErrors() : return the errors for all the invalid fields, that do not satisfy the validation.
getResult() : return full result. This includes all the fields(valid or invalid). If there is an error for the field then it is returned.
getMessages() : return all the error messages as an array.
<?php

// Create object of the class
$myObj = new MyClass("Test ABC");
$myObj->description = "Some desc string for testing";

// Call validation
$validationResponse = Validator::validate($myObj);

// Get the validation result using isValid() function
var_dump($validationResponse->isValid());

// Get the valiation result using getErrors() function
var_dump($validationResponse->getErrors());

// Get full result with errors and valid properties
var_dump($validationResponse->getResult());

// Get the erorr messages only
var_dump($validationResponse->getMessages());

Full Validation Example

Here is the full example of validation-

<?php

require_once "vendor/autoload.php";

use Webhkp\Pvalidate\Rules\Regex;
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 = 'aBCDE398';
}


// 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());

// Get full result with errors and valid properties
// var_dump($validationResponse->getResult());

// Get the erorr messages only
// var_dump($validationResponse->getMessages());

Output:

Here is the output of the above code-

bool(false)


array(5) {
  ["address"]=>
  array(3) {
    ["value"]=>
    NULL
    ["valid"]=>
    bool(false)
    ["errors"]=>
    array(1) {
      ["required"]=>
      string(25) "address field is Required"
    }
  }
  ["prop1"]=>
  array(3) {
    ["value"]=>
    int(40)
    ["valid"]=>
    bool(false)
    ["errors"]=>
    array(1) {
      ["min"]=>
      string(42) "prop1 should be larger than or equal to 50"
    }
  }
  ["prop2"]=>
  array(3) {
    ["value"]=>
    int(40)
    ["valid"]=>
    bool(false)
    ["errors"]=>
    array(1) {
      ["disallowed"]=>
      string(53) "prop2 should not be in the disallowed list (1,2,3,40)"
    }
  }
  ["myArr"]=>
  array(3) {
    ["value"]=>
    array(0) {
    }
    ["valid"]=>
    bool(false)
    ["errors"]=>
    array(1) {
      ["required"]=>
      string(23) "myArr field is Required"
    }
  }
  ["regexTestField"]=>
  array(3) {
    ["value"]=>
    string(8) "aBCDE398"
    ["valid"]=>
    bool(false)
    ["errors"]=>
    array(1) {
      ["regex"]=>
      string(52) "regexTestField should match the regex '/^[A-Z0-9]+/'"
    }
  }
}

Leave a Comment


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