PHP code example of crocodile2u / validity

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

    

crocodile2u / validity example snippets



use \validity\FieldSet, \validity\Field;

$name = Field::pattern("name", "/^[A-Z][a-zA-Z\- ]+$/")->setRequired();
$greeting = Field::enum("greeting", ["mr", "mrs"])->setRequired();
$subscriptions = Field::int("subscriptions")->setMin(1)->expectArray();
$email = Field::email("email")->setRequiredIf(
    function(FieldSet $fieldSet) {
        return (bool) $fieldSet->getFiltered("subscriptions");
    }
);
$dateOfBirth = Field::date("date_of_birth")->setMax("-18years")->setRequired();
$education = Field::string("education")
     ->setMinLength(10)
     ->setMaxLength(100)
     ->expectArray()
     ->setArrayMinLength(0)
     ->setArrayMaxLength(3)
     ->setArraySkipEmpty(true);

$fieldSet = (new FieldSet())
        ->add($name)
        ->add($greeting)
        ->add($subscriptions)
        ->add($email)
        ->add($dateOfBirth)
        ->add($education);

if ($fieldSet->isValid($_POST)) {
    $data = $fieldSet->getFiltered();
    // do something with $data
} else {
    // display errors summary
    echo $fieldSet->getErrors()->toString();
}

Field::string("username")->setRequired("Please enter username");

Field::email("email")->setRequiredIf(
    function(FieldSet $fieldSet) {
        return (bool) $fieldSet->getFiltered("subscriptions");
    }
);

Field::int("price")->setDefault(100, true, false);

Field::int("price")->setMin(1);
Field::date("date_of_birth")->setMax("-18years");

Field::string("name")
    ->setMinLength(2)
    ->setMaxLength(100);

Field::string("education")
    ->setMaxLength(100)
    ->expectArray()
    ->setArrayMinLength(0)
    ->setArrayMaxLength(3)

Field::string("username")
    ->addCallbackRule(
        function($value, FieldSet $fieldSet) {
            return !Users::usernameExists($value);
        }
    );

Field::int("subscriptions")->expectArray();

Field::int("subscriptions", "{label}: value #{key} is not an integer")
    ->setMin(1, "Subscriptions: value #{key} must be greater then or equal to {min}")
    ->expectArray()
    ->setArrayKeyOffset(1);

Field::string("email")->addCallbakRule(new EmailAddress(), "Email is invalid!");

Field::string("email")->addCallbakRule(function($value) {
    return (new EmailValidator())->validate($value);
}, "Email is invalid!");