PHP code example of simsoft / validator

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

    

simsoft / validator example snippets


use Simsoft\Validator;
use Simsoft\Validator\Rule;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;

$validator = Validator::make($_POST, [
    // bail: stops at first failure — only one error reported
    'email' => Rule::bail([
        new NotBlank(message: 'Email is eded',
        ),
    ],
]);

if ($validator->passes()) {
    $data = $validator->validated();
} else {
    echo $validator->errors()->first('email');
}

$validated = $validator->validated();              // all validated data
$email = $validator->validated('email');           // single attribute value

$data = $validator->safe()->only(['email']);       // subset of validated data
$data = $validator->safe()->except(['remember_me']); // exclude specific keys

foreach ($validator->safe() as $key => $value) {
    // iterate validated attributes
}

if ($validator->fails()) {
    echo $validator->errors()->first('email');     // first error for attribute
    $errors = $validator->errors()->all();         // all errors as an array
    $count = count($validator->errors());          // number of failed attributes

    if ($validator->errors()->has('email')) {
        // attribute has errors
    }

    foreach ($validator->errors()->get('email') as $message) {
        echo $message;                            // iterate attribute errors
    }

    foreach ($validator->errors() as $attribute => $messages) {
        // iterate all errors
    }
}

namespace App\Validators;

use Simsoft\Validator;
use Simsoft\Validator\Rule;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;

class LoginValidator extends Validator
{
    protected array $attributes = ['email', 'password', 'remember_me' => false];

    protected function rules(): array
    {
        return [
            'email' => Rule::bail([
                new NotBlank(message: 'Email is 

$validator = LoginValidator::make($_POST);

if ($validator->passes()) {
    $data = $validator->validated();
}