PHP code example of struktal / struktal-validation

1. Go to this page and download the library: Download struktal/struktal-validation 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/ */

    

struktal / struktal-validation example snippets


use struktal\validation\ValidationBuilder;
use struktal\validation\ValidationException;

$userInput = $_POST["input"];

// Create a validation builder instance
$validatedData = (new ValidationBuilder())
    // Define validation rules
    ->withErrorMessage("Input is missing")
    ->string()
    ->withErrorMessage("Input must be a string")
    ->minLength(5)
    ->withErrorMessage("Input must be at least 5 characters long")
    ->maxLength(10)
    ->withErrorMessage("Input must be at most 10 characters long")
    // Validate the input
    ->validate($userInput, function($e) {
        // Handle validation errors
        echo "Validation failed: " . $e->getMessage();
    });

// Do something with the validated data

use struktal\validation\ValidationBuilder;
use struktal\validation\ValidationException;

$userInput = $_POST;

$validatedData = (new ValidationBuilder())
    ->withErrorMessage("No POST data provided")
    ->array()
    ->children([
        "input" => (new ValidationBuilder())
            ->withErrorMessage("Input is missing")
            ->string()
            ->build(), // More rules could apply, also with explicit error messages
        "moreInput" => (new ValidationBuilder())
            ->withErrorMessage("More input is missing")
            ->int()
            ->minValue(0)
            ->maxValue(10)
            ->build(),
    ])
    ->withErrorMessage("Invalid POST data")
    ->validate($userInput, function($e) {
        // Handle validation errors
        echo "Validation failed: " . $e->getMessage();
    });

// Do something with the validated data