Giter Site home page Giter Site logo

awurth / slimvalidation Goto Github PK

View Code? Open in Web Editor NEW
66.0 5.0 23.0 190 KB

A wrapper around the Respect Validation PHP validation library for easier error handling and display

License: MIT License

PHP 100.00%
slim validation php twig-extension respect validator

slimvalidation's Introduction

Slim Validation

CI Latest Stable Version License

Total Downloads Monthly Downloads

A wrapper around the Respect Validation PHP validation library for easier error handling and display

This project was originally designed to be used with the Micro-Framework "Slim", hence the name "Slim Validation", but can now be used in any other PHP project.

Installation

$ composer require awurth/slim-validation

Documentation

  • 5.x (current, PHP >= 8.1)
  • 3.4 (outdated, PHP >= 7.1)

Usage

The following example shows how to validate that a string is at least 10 characters long:

use Awurth\Validator\Validator;
use Respect\Validation\Validator as V;

$validator = Validator::create();
$failures = $validator->validate('Too short', V::notBlank()->length(min: 10));

if (0 !== $failures->count()) {
    // Validation failed: display errors
    foreach ($failures as $failure) {
        echo $failure->getMessage();
    }
}

The validate() method returns a list of validation failures as an object that implements ValidationFailureCollectionInterface. If you have lots of validation failures, you can filter them with a callback:

use Awurth\Validator\ValidationFailureInterface;

$failures = $validator->validate(/* ... */);
$filteredFailures = $failures->filter(static function (ValidationFailureInterface $failure, int $index): bool {
    return $failure->getRuleName() === 'notBlank';
});

License

This package is available under the MIT license.

Buy Me A Coffee

slimvalidation's People

Contributors

alph44rchitect avatar awurth avatar deefuse avatar gomes81 avatar khrizt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

slimvalidation's Issues

When using a wrapper validator I'm getting null returned as the error message

When using a wrapper validator, like Optional, for example, I'm getting null returned as the error message text.

Here's an example:

// Validator container
$container['validator'] = function ($container) {
    $validator = new Awurth\SlimValidation\Validator();
    $validator->setDefaultMessages([
        'oneOf' => '{{name}} is not valid'
    ]);

    return $validator;
};


// -------------------------------------------------------------------


$validator = $this->container->validator->validate($request_body, [
    // optional
    'name' => Validator::Optional(Validator::notBlank())->setName('name')
]);

// If not valid, return error
if ( ! $validator->isValid()) {
    // Get first error and set as message
    $message = $validator->getFirstError(key($validator->getErrors()));
    echo $message;
}

Thanks

Validation of *oneOf*

Hi,

is there any way to validate with oneOf from the Respect validation package?

v::oneOf(
  v::key('ip', v::notBlank()),
  v::key('q', v::notBlank()->alpha()
)

Of course this works but does not contain validation messages like the validator method.

I'd like to pass this to the validator to get the error messages in case there are some.

$validator = $this->validator->validate($request, [
            'ip' => v::optional(v::ip()),
            'country' => v::optional(v::countryCode())->in($this->country_codes),
            v::oneOf(
                v::key('ip', v::notBlank()),
                v::key('q', v::notBlank()->alpha())
            )
        ]);

Thanks

Problem validation when use When and Key

Hi, first thank for the help.

I have the following data array:

$ values ​​["name"] = "second order";
$ values ​​["use_building"] = 8;
$ values ​​["other_use_building"] = "cave";

The validation has to check that when use_building is 8 the other_use_building is not empty.

If I perform the validation in a file for tests, the following validation works correctly:

$buildingValidator = v::key('use_building', v::optional(v::intVal()))
    ->when(v::key('use_building', v::equals(8)),
        v::key('other_use_building', v::notEmpty()),
        v::key('use_building', v::optional(v::intVal()))
    );

var_dump($buildingValidator->validate($values));

But when I enter it in the slim-validation system

return $this->validator->validate($values,
            [
                'name'    => ['rules' => V::notEmpty(),
                    'messages' => [
                        'notEmpty' => 'The name can not be left blank',
                    ]
                ],
                'use_building' => ['rules' => V::optional(V::intVal()->between(1, 8)),
                    'messages' => [
                        'intVal' => 'IT is not a valid type of use',
                        'between' => 'It is not a permitted use',
                    ]
                ],
                'other_use_building' => [ 'rules' => V::key('use_building', V::optional(V::intVal()->between(1, 8)))
                    ->when(V::key('use_building', V::equals(8)),
                        V::key('other_use_building', V::notEmpty()),
                        V::key('use_building', V::optional(v::intVal()))
                    ),
                    'messages' => [
                        'notEmpty' => 'The Other user buildin can not be left blank',
                    ]
                ]
            ]);

tells me what error when he had to see given true

{
    "errors": {
        "other_use_building": {
            "key": "Key use_building must be present"
        }
    }
}

Thanks for the help

Validate subdivisionCode fails

TypeError: Argument 1 passed to Awurth\SlimValidation\Validator::getRulesNames() must be an instance of Respect\Validation\Rules\AllOf, instance of Respect\Validation\Rules\SubdivisionCode\UsSubdivisionCode given, called in .\vendor\awurth\slim-validation\src\Validator.php on line 542

My code is like this:

$input['subdivision'] = 'US-CA';

$rules['subdivision'] = [
    'rules' => new Respect\Validation\Rules\AllOf(
        new Respect\Validation\Rules\NotBlank(),
        new Respect\Validation\Rules\SubdivisionCode('US')
    )
];

$validator = new Validator();

$validator->validate($input, $rules);

Thanks for your help.

Problem with PHP 8.0

After upgrade to PHP 8.0, it's popped up an error message to do Composer update.

 Problem 1
    - awurth/slim-validation[3.0.0, ..., 3.3.0] require php ^7.0 -> your php version (8.0.2) does not satisfy that requirement.
    - Root composer.json requires awurth/slim-validation >=3.0 -> satisfiable by awurth/slim-validation[3.0.0, ..., 3.3.0].

Please add the support to PHP 8.0. Thanks a lot.

Custom rules

Hi,
It is an interesting integration of Respect Validation with Slim, but I do not see any method or way to load own rules, which would be interesting for verifications with database or something else.

Thanks for the collaboration

Problem validation file()->uploaded()->image()

Hey. Validator does not work with files. But, maybe I did not find how to work.

       $validateData = [
            'room_category_id' => v::intVal()->setName('ИД категории'),
            'type' => v::in(['1', '2', '3', '4'])->setName('Тип чата'),
            'access' => v::in(['link', 'public'])->setName('Тип доступа к чату'),
            'password' => v::noWhitespace()->setName('Пароль чата'),
            'starts_at' => v::date('Y-m-d H:i')->setName('Время старта события'),
            'ends_at' => v::date('Y-m-d H:i')->setName('Время окончания события'),
        ];
        if (!empty($uploadedFiles['image']->file)) {
            $validateData['image'] = v::file()->uploaded()->image()->CheckFile($uploadedFiles['image']->file)->setName('Файл');
        }        
        $validation = $this->validator->validate($request, $validateData);

I temporarily solved the problem)
file Validator.php

public function validate(Request $request, array $rules, array $messages = []) {
        foreach ($rules as $param => $options) {
            $uploadedFiles = $request->getUploadedFiles();
            $value = $request->getParam($param) ?? $uploadedFiles[$param]->file ?? null;
            try {
                if ($options instanceof RespectValidator) {
                    $options->assert($value);
                } else {
                    if (!is_array($options) || !isset($options['rules']) || !($options['rules'] instanceof RespectValidator)) {
                        throw new InvalidArgumentException('Validation rules are missing');
                    }
                    $options['rules']->assert($value);
                }
            } catch (NestedValidationException $e) {

Add required option

Add required option to validate an imput only if it comes within the request parameters for example:

validator = $this->validator->validate($params, [
'username' => V::length(2, 25)->alnum('')->noWhitespace(),
'full_name' => V::length(2, 25)->alnum('')->required(false),
'password_hash' => V::length(8, 25)->alnum('')->noWhitespace(),
'email' => V::email()
]);

->required(false) will only validate if the $request has the full_name parameter, could also be named - >notRequired()

Set a Error Message

I`ve the follow logic in my controller: if condition is true then proceed. Else if not and other condition ok, I do set a error in errors of validator. How I can build this?

   $this->validator->validate($p, [
           'field_not_blank' => V::notBlank(),
            'field_email' => V::notBlank()->email(),
             'num_field' => V::notBlank()->numeric()
    ]);
    $AnyService = ($this->validator->isValid()) ? new Service($args) : null ;
    if ($this->validator->isValid()) {
      if ( CONDITION_OK ) {
          // code ok
      }
    }elseif(CONDICTION_ELSE_IF)) {
      // add error to validator
    }

Validate a value only when the key exists

I have a form with which a user can update an entry in the database using a PATCH request.

This patch request only submits the modified field values (not the entire object).

Some fields are mandatory and require a value but it is possible that these field values are not present in the request data.

How can I perform validation only on the field values which are present in the request data?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.