PHP code example of jasny / validation-result

1. Go to this page and download the library: Download jasny/validation-result library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jasny / validation-result example snippets


use Jasny\ValidationResult;

function validateVar($var)
{
    if (isset($var)) return ValidationResult::error("var isn't set");
    if ($var < 30) return ValidationResult::error("var is less than thirty");
    
    return ValidationResult::success();
}

$validation = validateVar($myVar);
if ($validation->failed()) echo $validation->getError();

use Jasny\ValidationResult;

function validateInput($input)
{
    $validation = new ValidationResult();

    if (!isset($input['baz'])) $validation->addError("baz isn't set");
    if (!isset($input['qux'])) $validation->addError("qux isn't set");
  
    return $validation;
}

$validation = validateInput($_POST);

if ($validation->succeeded()) {
    // Handle POST and redirect
    exit();
}

loadTemplate('myTemplate', ['errors' => $validation->getErrors()]);

use Jasny\ValidationResult;

function validateInput($input)
{
    $validation = new ValidationResult();

    if (!isset($input['baz'])) $validation->addError("baz isn't set");
    if (!isset($input['qux'])) $validation->addError("qux isn't set");
  
    if (isset($input['foo'])) {
        $fooValidation = validateFoo($input['foo']);
        $validation->add($fooValidation, 'foo');
    }
  
    return $validation;
}

function validateFoo($foo)
{
    $validation = new ValidationResult();
    
    if (empty($foo['name'])) $validation->addError("name isn't set");
    if (empty($foo['age'])) $validation->addError("age isn't set");
    
    return $validation;
}

$validation = validateInput($_POST);

use Jasny\ValidationResult;

$aliases = [
    "%s isn't set" => 'Please set %s',
    "%s is less than %d" => 'Please choose a value higher than %2$d for %1$s'
];

ValidationResult::$translate = function($message) use ($aliases) {
    return isset($aliases[$message]) ? $aliases[$message] : $message;
};

function validateVar($var)
{
    if (isset($var)) return ValidationResult::error("%s isn't set", 'Var');
    if ($var < 30) return ValidationResult::error("%s is less than %d", 'Var', 30);
}

ValidationResult::$translate = 'gettext';