Pvalidate: Individual Rule Validation

We can use the rules individually to parse some data.

Parsing Methods

To parse we have two functions-

parse() : parse data and throw an exception if there is any error.
safeParse() : parse data and return result (do not throw exception).

Examples

Here are a few examples of using the rules individually to parse and validate data-

Required Validation

To validate if a field is required, use the Required rule. This example demonstrates how to validate a null value, which should fail the validation.

use Webhkp\Pvalidate\Rules\Required;

try {
    $requiredValidationResult = (new Required())->parse(null);

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

Output:

string(18) " field is Required"

int(1)

object(Webhkp\Pvalidate\Exceptions\PvalidateException)#12 (8) {
  ["message":protected]=>
  string(18) " field is Required"
  ["string":"Exception":private]=>
  string(0) ""
  ["code":protected]=>
  int(1)
  ["file":protected]=>
  string(80) "pvalidate/src/Rules/ValidationRule.php"
  ["line":protected]=>
  int(72)
  ["trace":"Exception":private]=>
  array(1) {
    [0]=>
    array(5) {
      ["file"]=>
      string(43) "index.php"
      ["line"]=>
      int(127)
      ["function"]=>
      string(5) "parse"
      ["class"]=>
      string(37) "Webhkp\Pvalidate\Rules\ValidationRule"
      ["type"]=>
      string(2) "->"
    }
  }
  ["previous":"Exception":private]=>
  NULL
  ["additionalData":"Webhkp\Pvalidate\Exceptions\PvalidateException":private]=>
  NULL
}

Regex Validation

To validate a value against a regular expression, use the Regex rule. This example validates a string that should match the regex pattern /^[A-Z0-9]{3}.*/.

use Webhkp\Pvalidate\Rules\Regex;

// 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(1) {
  ["regex"]=>
  string(42) " should match the regex '/^[A-Z0-9]{3}.*/'"
}

Leave a Comment


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