Coder Social home page Coder Social logo

siriusphp / validation Goto Github PK

View Code? Open in Web Editor NEW
159.0 11.0 29.0 617 KB

Framework agnostic validation library for PHP

Home Page: http://www.sirius.ro/php/sirius/validation/

License: MIT License

PHP 100.00%
php validation security input sanitization forms

validation's Introduction

Sirius Validation

Source Code Latest Version Software License Build Status Coverage Status Quality Score Total Downloads

Sirius Validation is a library for data validation. It offers:

  1. validator object
  2. 45 build-in validation rules. There are validators for strings, array, numbers, emails, URLs, files and uploads
  3. validation helper to simplify the validation of single values

Out-of-the-box, the library can handle arrays, ArrayObjects and objects that have implemented the toArray method. In order to validate other data containers you must create a DataWrapper so that the validator be able to extract data from your object.

Elevator pitch

$validator = new \Sirius\Validation\Validator;

// add a validation rule
$validator->add('title', 'required');

// add a rule that has a list of options
$validator->add('title', 'length', array('min' => 10, 'max' => 100));
// or use JSON
$validator->add('title', 'length', '{"min": 10, "max": 100}');
// or a URL query string
$validator->add('title', 'length', 'min=10&max=100');
// or, if you know that the validator can CORECTLY parse (ie: understand) the options string
$validator->add('title', 'length', '10,100');

// add a rule with a custom error message
$validator->add('title', 'maxlength', 'max=100', 'Article title must have less than {max} characters');

// add a rule with a custom message and a label (very handy with forms)
$validator->add('title:Title', 'maxlength', 'max=100', '{label} must have less than {max} characters');

// add multiple rules at once (separate using [space][pipe][space])
$validator->add('title:Title', 'required | maxlength(255) | minlength(min=10)');

// add all your rules at once
$validator->add([
        'title:Title' => 'required | maxlength(100)',
        'content:Content' => 'required',
        'source:Source' => 'website'
    ], [
        'content.required' => 'The content field should have a velue'
    ]);

// add nested rules
$validator->add('recipients[*]:Recipients', 'email'); //all recipients must be valid email addresses
$validator->add('shipping_address[city]:City', 'MyApp\Validator\City'); // uses a custom validator to validate the shipping city

Links

validation's People

Contributors

adrianmiu avatar amirkhiz avatar bokunodev avatar bradchesney79 avatar eclipxe13 avatar everon avatar filisko avatar gajus avatar gumacs92 avatar kenjis avatar kulavvy avatar mickrip avatar nanawel avatar rhilip avatar sergiobelya avatar tichael avatar userlond avatar vikkio88 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  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  avatar  avatar  avatar  avatar  avatar  avatar

validation's Issues

Validation failing for empty values

Unless I am missing something, most rules should not be validated (or validation should return true) if the input is null or an empty string (except for Required, Length and some others).

Here is an example where Email, AlphaNumeric, AlphaNumHyphen and Alpha is failing validation, but is not required:

<?php

require 'vendor/autoload.php';

$input = [
  'name' => 'Christiaan',
  'email' => '',
  'address' => [
    'line_1' => '',
    'line_2' => '',
    'country' => ''
  ]

];

$validator = new Sirius\Validation\Validator;

$validator
  ->add('name', ['Required', 'AlphaNumeric'])
  ->add('email', ['Email'])
  ->add('address[line_1]', ['AlphaNumeric'])
  ->add('address[line_2]', ['AlphaNumHyphen'])
  ->add('address[country]', ['Alpha'])
  ->validate($input);

?>

<pre><?php print_r($validator->getMessages()); ?></pre>

Returns:

Array
(
    [email] => Array
        (
            [0] => Sirius\Validation\ErrorMessage Object
                (
                    [template:protected] => This input must be a valid email address
                    [variables:protected] => Array
                        (
                            [value] => 
                        )

                )

        )

    [address[line_1]] => Array
        (
            [0] => Sirius\Validation\ErrorMessage Object
                (
                    [template:protected] => This input can contain only letters and digits
                    [variables:protected] => Array
                        (
                            [value] => 
                        )

                )

        )

    [address[line_2]] => Array
        (
            [0] => Sirius\Validation\ErrorMessage Object
                (
                    [template:protected] => This input can contain only letters, digits, spaces, hyphens and underscores
                    [variables:protected] => Array
                        (
                            [value] => 
                        )

                )

        )

    [address[country]] => Array
        (
            [0] => Sirius\Validation\ErrorMessage Object
                (
                    [template:protected] => This input can contain only letters
                    [variables:protected] => Array
                        (
                            [value] => 
                        )

                )

        )

)

Add a rule to check against white list

Is there a way to check against a list of values inside an array. E.g.

$acceptedValues = array("value1","value2");

Only validate if user input is equal to what's inside an array

getMessages returns unformatted message

Hi when I try to retrieve errors with $validator->getMessages()

I get a unformatted response. I've reverted back to an older version where this does not happen.

I'm referring to this part: {label} is required

        [0] => Sirius\Validation\ErrorMessage Object
            (
                [template] => {label} is required
                [variables] => Array
                    (
                        [label] => Name
                        [value] => 
                    )
            )

case:

        $validator->add(array(
            'name:Name' => 'required | maxlength(100)',
            'username:Username' => 'required | maxlength(100)',
        ));

RequiredWith and extra validation not working as expected

Hello, I'm creating a middleware that implements your validation. Unfortunately, I'm having issues with a mixed validation.
Hopefully, you can help me out.
My rules are:

$validator = new \Sirius\Validation\Validator();
$validator->add(
    [
        'latitude' => ['requiredWith(longitude)', 'number'],
        'longitude' => ['requiredWith(latitude)', 'number']
    ]
);

$result = $validator->validate([]);
var_dump($result); // Returns false

In theory, the number rule should be checked for both latitude and longitude, if any of the two is passed, but it reality it does not and validate returns false.

Am I setting the rules incorrectly or is this the expected behaviour?

I'm running version 2.2, PHP 7.1

undefined method getMessage()

Error: Call to undefined method Sirius\Validation\Validator::getMessage()

the function is not defined in Sirius\Validation\Validator

length / regex not working as expected

Greets

I'm trying out Sirius/Validation for the first time but experiencing an issue or two.

Version: 2.2

In my case, the length(10,32) and regex() are not validating as expected:

    <?php

    require_once("vendor/autoload.php");

    use Sirius\Validation\Validator;

    $data =<<<EOD
    {
        "method": "create",
        "backend": {
            "client": "my&"
        }
    }
    EOD;
    $data = json_decode($data,true);

    $validator = new Validator();
    $validator->add('method', 'required');
    $validator->add('method', 'inlist', array('list'=>array('create',)));
    $validator->add('backend', 'arraylength', array('min'=>1,'max'=>1));
    $validator->add('backend[*]client', 'required');
    $validator->add('backend[*]client', 'length', array('min'=>10,'max'=>32));  // FAILS TO VALIDATE
    $validator->add('backend[*]client', 'regex', '/^[a-z0-9-]+$/');  // FAILS TO VALIDATE

    if ($validator->validate($data)) {
        print "OK\n";
    } else {

        // send the error messages to the view
        print_r($validator->getMessages());

    }

I'd appreciate any pointers.

Thanks
Henry

bugs on getMessages()

this function only returns erros on the first element when trying to validate a data array(), and the custom error message is not parsed nore taken into account

for something like
array('name', 'required | maxlength(max=25) | minlength(min=3)({label} must have between {min} and {max} characters)(Name)',
'activity', 'required | maxlength(max=25) | minlength(min=3)({label} must have between {min} and {max} characters)(Activity)');

I get

array(1) { ["name"]=> array(1) { [0]=> object(Sirius\Validation\ErrorMessage)#713 (2) { ["template":protected]=> string(22) "This field is required" ["variables":protected]=> array(1) { ["value"]=> string(0) "" } } } }

"AlphaNumHyphen" did not type control

Hello,

When i used "AlphaNumHyphen" validator for an array object, php has gave a notice and it's validation returned true.

$object = ['array' => ['field1', 'field2']];
$validation->add('array', 'required');
$validation->add('array', 'AlphaNumHyphen');
$validation->validate($object);

"A PHP Error was encountered

Severity: Notice

Message: Array to string conversion

Filename: Rule/AlphaNumHyphen.php

Line Number: 23"

and return true.

PHP Version: 5.6
Sirius/validation: 2.1.2

Improve IDE support

Use constants for the rules

$validator->add('email_address', Validator::RULE_EMAIL);

A warning thrown in php 8.1.7

Bug Report

Q A
BC Break yes
Version 3.0.2 and dev-master

Summary

nothing fancy, i'm just trying to validate an array and the error (warn) happen.
and this is the log.

Deprecated: Return type of Sirius\Validation\RuleCollection::attach($rule, $data = null) should either be compatible with SplObjectStorage::attach(object $object, mixed $info = null): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /home/boku/Public/php-sandbox/adr-skeleton/vendor/siriusphp/validation/src/RuleCollection.php on line 8

Deprecated: Return type of Sirius\Validation\RuleCollection::getHash($rule) should either be compatible with SplObjectStorage::getHash(object $object): string, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /home/boku/Public/php-sandbox/adr-skeleton/vendor/siriusphp/validation/src/RuleCollection.php on line 30

How to reproduce

i have this code in slim 4 controller and serve it with php (PHP 8.1.7) dev server.

$input = [
    'email'=>'email@me',
];

$this->valid->add('email', ['required', 'email']);
$data = $this->valid->validate($input);

var_dump($data);
var_dump($input);

Reduce the amount of code repeat on labels

When a value selector has different validation rules and you want to customize the error message with the label you have to provide the label multiple times

$validator->add(array(
  'preference[*][notification][after][timeout]' => array(
     array('required', null, '{label} is required', 'After Timeout'), 
     array('Number', null, '{label} must be a valid number', 'After Timeout'))
 ));

Implement a way to reduce this code.

Filtering out unknown elements

It would be awesome if Validator would also filter out unknown elements and provide filtered input.

An example should sched some light:

$data = [
  'id' => '123',
  'email' => '[email protected]',
  'text' => 'some text here',
  'submit' => 'Send',
  'some_value_user_posted' => '123',
  // other unknown/unused fields
];

$validator = new \Sirius\Validation\Validator();

$validator->add([
  'id' => 'required|number',
  'email' => 'required|email',
  'text' => 'required'
]);

if(!$validator->validate($data)){
  send_errors($validator->getMessages());
}else{
  $clean_data = $validator->data();
  // and $clean_data contains only id, email and text, nothing else
}

No message when json_encode($validator->getMessages())

Scenario: I'm developing an API-centric application so every form submission are done in AJAX. The response headers are application/json so I need to json_encode the data. But that causes the messages in the validator to output nothing.

I have a dirty workaround for this.

    /**
     * Format messages and make them string for json output.
     *
     * @param array $messages
     * @return array
     */
    protected function formatMessagesForJsonOutput(array $messages)
    {
        $formatter = function ($value)
        {
            return (string) $value[0];
        };

        return array_map($formatter, $messages);
    }

It would be great if the library automatically convert the error messages into string for json_encode.

Only evaluating the first rule?

Hi,

Either I'm missing something completely obvious or might there be bug in the version 2.1.
It seems that, when passing an array to the add method, it only adds or evaluates the first rule.

    $validator = new Validator();

    $input = ['title' => 'Some title'];

    $validator->add(array(
        'title:Title' => 'required',
        'content:Content' => 'required | minlength(5)',
    ));

    if ($validator->validate($input)) {
        echo "all good";
    } else {
       var_dump($validator->getMessages();
    }

If you run this code, it returns true even though the content is not included in the $input array. But the funny thing is, even if I change the $input to:

    $input = ['title' => 'Some title', 'content'  => 'foo'];

This still returns true, even though content is less than 5 chars.

What am I missing?

thanks,

Contribution guide?

Hi, I would like to participate in your project, do you have a contribution guide? to-do list? or some info I could use to help?

I think you maintain compatibility with PHP 5.3 because of WP. Is my assumption right?

Have you consider open a communication line like gitter?

These are some ideas:

  • setup phpunit testing (like phpunit.dist.xml in the root)
  • setup project files more standard (follow pds/skeleton?)
  • fix phpcpd issues
  • improve travis-ci (set sudo false, post code coverage only on one php run)

Rule Length incorrect

in code of rule Length, in function validate, use incorrect class for max and min validator
$maxValidator = new MinLength();
$minValidator = new MaxLength();

need use MaxLength for $maxValidator, and MinLength for $minValidator

Regex pattern containing braces parced incorrectly

If i add rule

regex((\+7)?\d\d\d-\d\d\d\d\d\d\d)

then i got Regex rule with just (\+7 parsed.

As temporarily workaround i'd preferred to add some rules in list of addMultiple() as Regex instances. But it is also impossible for now :(

Implement some conditional rules

  1. RequiredWith (when another item is present/not null)
  2. RequiredWithout - inverse to 1
  3. RequiredWhen (when another item has a specific value)

Typo in validatorsMap

In line 32 of RuleFactory, there is a typo in Validator::RULE_ARRAY_MIN_LENGTH => 'ArrayMinLengh',. It should be ArrayMinLength.

Rule GreaterThan(0) is not work

And another rules that may contain value 0 as param are not working (likely).
This is related for rules that declared as a string.
Cause, see
ValueValidator::parseRule() - https://github.com/siriusphp/validation/blob/2.2.0/src/ValueValidator.php#L220
and
AbstractRule::normalizeOptions() - https://github.com/siriusphp/validation/blob/2.2.0/src/Rule/AbstractRule.php#L93

Row

if (isset($matches[1][0]) && $matches[1][0]) {

may be replace to

if (isset($matches[1][0]) && $matches[1][0] !== '') {

but

if (! $options) {

I don't know how to fix it correctly.

Post back fields

Hello there, thanks for the brilliant library. I wanted to know if there is a built in way to post back passed values to the form if some fail validation e.g. in a form of 3 inputs 2 passed and 1 failed, when the user returns to the form after validation the passed fields are already filled in. Hope that makes sense. Cheers

build-in rule URI throw exception in PHP 7.3

When use build-in ruls Url in PHP 7.3 , it will throw Exception:

filter_var(): explicit use of FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED is deprecated

Refer

Solution

From PHPMailer/PHPMailer#1551 , I hope this patch can help you fix this bug:

Index: vendor/siriusphp/validation/src/Rule/Url.php
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- vendor/siriusphp/validation/src/Rule/Url.php	(date 1560607388394)
+++ vendor/siriusphp/validation/src/Rule/Url.php	(date 1560607388394)
@@ -9,7 +9,7 @@
     public function validate($value, $valueIdentifier = null)
     {
         $this->value   = $value;
-        $this->success = (bool) filter_var($value, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);
+        $this->success = (bool) filter_var($value, FILTER_VALIDATE_URL);
 
         return $this->success;
     }

Integrate Filtration into validation Syntax?

Would it be possible to use filtration inside the same rule syntax?

$validator->add('title', 'required | maxlength(max=255) | minlength(min=10) | sirius(strip_tags)');

Thanks for putting work into this, useful class which I'll be using.

Get rid of ensureRequiredItems() method

Because we have conditional required rules we need to set item values to NULL for those rules as well. This is prone to error, so we need to work with whatever data we receive and not set NULL values when some items are missing

file upload and date

Question

Hi I am using the latest version of this and trying to validate an uploaded file and date like so:

$validator->add(
		[
			'learner-name:Name' => 'required',
			'learner-license:License number' => 'required',
			'learner-email:Email' => 'required | email',
			'learner-mobile:Mobile' => 'required | minlength(11)',
			'learner-ted:Theory expiry date' => 'date',
			'learner-dlp:License Photo' => 'upload\required | upload\image',
			'course-id:Course not chosen' => 'integer'
		]
	);

The date field throws an error:
Warning: date() expects at most 2 parameters, 3 given any format I send gives that warning.
And the file upload never gets evaluated, am I missing something?

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.