Code Monkey home page Code Monkey logo

zend-validator's Introduction

zend-validator

Repository abandoned 2019-12-31

This repository has moved to laminas/laminas-validator.

Build Status Coverage Status

zend-validator provides a set of commonly needed validators. It also provides a simple validator chaining mechanism by which multiple validators may be applied to a single datum in a user-defined order.

Installation

Run the following to install this library:

$ composer require zendframework/zend-validator

Documentation

Browse the documentation online at https://docs.zendframework.com/zend-validator/

Support

zend-validator's People

Contributors

akrabat avatar bakura10 avatar breyndotechse avatar cgmartin avatar dasprid avatar dchusovitin avatar dragonbe avatar evandotpro avatar ezimuel avatar freeaqingme avatar froschdesign avatar koopzington avatar localheinz avatar maks3w avatar marc-mabe avatar michalbundyra avatar mikaelkael avatar mpinkston avatar mwillbanks avatar ocramius avatar ralphschindler avatar samsonasik avatar sgehrig avatar thinkscape avatar thomasweidner avatar veewee avatar victory avatar wdalmut avatar weierophinney avatar xerkus 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

zend-validator's Issues

StaticValidator test is incorrect (false positive)

Opening an issue as a result of findings in my pull request #15. Here the issue has been removed, but not explicitly addressed.

There is a test in StaticValidatorTest (and ValidatorChainTest) which test the StaticValidator and Between:

    public function testExecuteValidWithParameters()
    {
        $this->assertTrue(StaticValidator::execute(5, 'Between', [1, 10]));
        $this->assertTrue(StaticValidator::execute(5, 'Between', ['min' => 1, 'max' => 10]));
    }

The first assertion implies (or at least creates some confusion, as evidenced in the pull request) that you can pass an array of options in, and they are passed to the actual validator as individual parameters. This is definitely not the case.
In this example, the Between validator will end up with an option called '0', with a value of '1', and an option called '1', with a value of '10'. The test currently passes, because the Between validator has a default value for min and max (0 and PHP_INT_MAX respectively).

To show more detail:

 % php -a
Interactive mode enabled

php > require_once "vendor/autoload.php";
php > var_dump(\Zend\Validator\StaticValidator::execute(5, 'Between', ['min' => 1, 'max' => 10]));
bool(true)
php > var_dump(\Zend\Validator\StaticValidator::execute(0, 'Between', ['min' => 1, 'max' => 10]));
bool(false)
php > var_dump(\Zend\Validator\StaticValidator::execute(100, 'Between', ['min' => 1, 'max' => 10]));
bool(false)
php > var_dump(\Zend\Validator\StaticValidator::execute(5, 'Between', [1, 10]));
bool(true)
php > var_dump(\Zend\Validator\StaticValidator::execute(0, 'Between', [1, 10]));
bool(true)
php > var_dump(\Zend\Validator\StaticValidator::execute(100, 'Between', [1, 10]));
bool(true)
php > $validator = new \Zend\Validator\Between([1, 10]);
php > var_dump($validator);
class Zend\Validator\Between#2 (5) {
  protected $messageTemplates =>
  array(2) {
    'notBetween' =>
    string(57) "The input is not between '%min%' and '%max%', inclusively"
    'notBetweenStrict' =>
    string(53) "The input is not strictly between '%min%' and '%max%'"
  }
  protected $messageVariables =>
  array(2) {
    'min' =>
    array(1) {
      'options' =>
      string(3) "min"
    }
    'max' =>
    array(1) {
      'options' =>
      string(3) "max"
    }
  }
  protected $options =>
  array(5) {
    'inclusive' =>
    bool(true)
    'min' =>
    int(0)
    'max' =>
    int(9223372036854775807)
    [0] =>
    int(1)
    [1] =>
    int(10)
  }
  protected $value =>
  NULL
  protected $abstractOptions =>
  array(7) {
    'messages' =>
    array(0) {
    }
    'messageTemplates' =>
    array(2) {
      'notBetween' =>
      string(57) "The input is not between '%min%' and '%max%', inclusively"
      'notBetweenStrict' =>
      string(53) "The input is not strictly between '%min%' and '%max%'"
    }
    'messageVariables' =>
    array(2) {
      'min' =>
      array(1) {
        ...
      }
      'max' =>
      array(1) {
        ...
      }
    }
    'translator' =>
    NULL
    'translatorTextDomain' =>
    NULL
    'translatorEnabled' =>
    bool(true)
    'valueObscured' =>
    bool(false)
  }
}

I should point out that in my pull request, I have removed this assertion from the tests, as the Between validator no longer has default values.

Check Documentation Code Blocks

Check code blocks are correct

TLDR; Check in all files that codeblocks are correct, in PSR-2 format and have PHP syntax highlighting applied.

Code blocks should be in the following format...

```php
 'ZEND-FRAMEWORK');

// No required options
$rendererOptions = array();
$renderer = Barcode::factory(
    'code39', 'image', $barcodeOptions, $rendererOptions
);

```

Note the three backticks then php in the opening fence, and the closing fence is just three backticks. It's common for the opening backticks to have no code type, or something like source.

Code should also have been automatically formatted into PSR-2 format, but sometimes these slip through the net.

Validator Time issue

I try to use the Time FormElement.
\zend-validator\src\DateStep will throw everytime an error at
$absoluteBaseDate = new DateTime($baseDate->format('Y-m-d H:i:s'), new DateTimeZone('UTC'));

Call to a member function format() on boolean

it seems like that
$baseDate = $this->convertToDateTime($this->baseValue, false);

returns a false if the baseValue is a time (00:00:00).

[ZF3][RFC] Refactoring the Hostname validator

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7312
User: @moderndeveloperllc
Created On: 2015-03-11T16:40:18Z
Updated At: 2015-11-06T22:05:34Z
Body
It looks like I may have time available to do a long needed refactoring of the Hostname validator. I would like feedback from the core contributors when it comes to the desirability of certain options.

Why is a refactoring needed?

  • Length and positional validations are currently being done on the composed Unicode encoding of domains and TLDs. All length requirements are based on the ACE of the name.
  • Not nearly enough IDN domain info. There are many, many more domain tables. This brings into question the current system for storing this info.
  • The class currently assumes PCRE Unicode support without testing for it.
  • There is currently a homegrown function that replicates idn_to_utf8() functionality, but none for idn_to_ascii().
  • There is no way to specify a language restriction for a TLD (Only check Icelandic characters for this .com domain)
  • There is no option to see if the hostname actually exists via something like checkdnsrr().

I propose that this validator either:

a) Me moved over to the Zend\I18n\Validator namespace so we can be assured of the intl extension.

b) Split the class - Have a non-IDN version in Zend\Validator for use by developers who don't deal with IDN domains, and a version in Zend\I18n\Validator that includes all the IDN files, manipulation, etc.

or

c) Write intl-checking logic into a class in Zend\Validator. If we don't have that or PCRE Unicode support, only check non-IDN domains and characters.

The first option has the value of being DRY'er by not replicating much of the same code. With ZF3 trying to remove inter-module dependancies, I'm not sure you would want to add Zend\Validator as a requirement to the Zend\I18n module. The second option would probably result in faster code for a majority of users by not including lots of logic and data for every domain check. For instance, if no language is specified, you could be checking upwards of 100 character sets for domains in the .com TLD. The third option would have code that is a bit more complex, and and you are bringing Zend\I18n\Validator-type functions into the Zend\Validator namespace.

The downside of option a) is that there is now another module to add (Zend\I18n) for any dev who wants to check hostnames - even if they are not doing any I18n. The issue with b) is that it isn't DRY, and will require more maintenance, testing, etc.

Questions for Core Developers

  • Are these valid reasons to take the time and rewrite everything, or is the current class structure fine?
  • Do I split the Hostname validation code into two classes, move it into Zend\I18n\Validator, or try and write intl-checking logic into a class in Zend\Validator?
  • Would you want a separate HostnameExists class for checkdnsrr()-style checking, or as an option to the Hostname class?
  • Any thoughts on data storage? I know that loading files from the harddrive is slow, but I don't think we can realistically stuff this class with the > 1MB of data that all these code tables contain.

TODOs:

  • Decide to split or not split the class
  • Figure out how to store IDN information
  • Write tests
  • Code the validation logic for the class (or two!)
  • Add (optional) caching logic for data files.
  • Add new Zend\Validator\HostnameExists class to check for existing records?

It should be noted that this validator can only check if the domain/IP/URI is properly formatted with the correct characters. It will not check to see if the domain is actually permissible by the TLD registrar. Many gTLD registrars have rules that are beyond the scope of any general validator. For instance, many IDN registrars will not allow you to register domains that have codepoints that are variants of existing domains.

[Edit to add permissibility paragraph at bottom -MDG]


Comment

User: @moderndeveloperllc
Created On: 2015-03-11T16:43:00Z
Updated At: 2015-03-11T16:43:00Z
Body
ping @DASPRiD, @Ocramius


Comment

User: @moderndeveloperllc
Created On: 2015-03-17T19:09:02Z
Updated At: 2015-03-17T19:09:02Z
Body
@weierophinney Should I pursue this, or am I just looking to do something that will be invalidated by other ZF3 changes in teh future?


Comment

User: @moderndeveloperllc
Created On: 2015-04-09T20:35:36Z
Updated At: 2015-04-09T20:35:36Z
Body
@DASPRiD, @Ocramius is this something I should pursue? Don't want to spend a big chunk of time to do this if it's already being done.


Comment

User: @RalfEggert
Created On: 2015-04-22T08:54:53Z
Updated At: 2015-04-22T08:54:53Z
Body
Should be marked for ZF3 milestone, shouldn't it?


Comment

User: @weierophinney
Created On: 2015-06-25T22:44:28Z
Updated At: 2015-06-25T22:44:28Z
Body
@moderndeveloperllc I'd open new PRs against:

and discuss in those. I personally prefer having all the validators in one package, with defined optional dependencies specified for validators that need them (I'd argue the same for filters and other plugins, too); when I look for a validator, I'm not looking in zend-i18n, I'm looking in zend-validator.

Other than that, I think the refactor seems reasonable.


Local EmailAdress Validator Problems (Windows)

Hey there!

If i attach following validator to my validator chain and validate emails like [email protected] or [email protected] or simply my own domain i will get the Validator\EmailAddress::INVALID_SEGMENT message printed.

new Validator\EmailAddress(
    [
        'useDeepMxCheck' => true,
        'useDomainCheck' => true,
        'useMxCheck'     => true
    ]
)

I debugged the code and found out that the call of $result = getmxrr($this->idnToAscii($this->hostname), $mxHosts, $weight); in method validateMXRecords() will return true but the $mxHosts and $weight is empty. Thats why the isValid() return false. I tested it under Windows, linux and Macintosh. Linux and Macintosh works great but Windows fails.

I tried to use $result = dns_get_record($this->idnToAscii($this->hostname), DNS_MX, $mxHosts, $weight); instead but then my php-cgi quits.

Linux/Macintosh:

php -r '$mxHosts = [];$weight  = [];$result = getmxrr("googlemail.com", $mxHosts, $weight);var_dump($result, $mxHosts, $weight);'
bool(true)
array(5) {
  [0]=>
  string(31) "alt1.gmail-smtp-in.l.google.com"
  [1]=>
  string(31) "alt4.gmail-smtp-in.l.google.com"
  [2]=>
  string(31) "alt3.gmail-smtp-in.l.google.com"
  [3]=>
  string(31) "alt2.gmail-smtp-in.l.google.com"
  [4]=>
  string(26) "gmail-smtp-in.l.google.com"
}
array(5) {
  [0]=>
  int(10)
  [1]=>
  int(40)
  [2]=>
  int(30)
  [3]=>
  int(20)
  [4]=>
  int(5)
}

Windows:

php -r '$mxHosts = [];$weight  = [];$result = getmxrr("googlemail.com", $mxHosts, $weight);var_dump($result, $mxHosts, $weight);'
bool(true)
array(0) {
}
array(0) {
}

NotEmpty __construct creates bitmap incorrectly

When constructing a NotEmpty validator with an array of types, the constructor adds the bitmaps instead of bit-oring them like calculateTypeValue. It's only an issue if overlapping types such as 'php' and 'boolean' are specified, but I imagine this would be a pain to debug if anyone ever runs into it.

As shown in the documentation:

$validator = new Zend\Validator\NotEmpty(array(
    'boolean',
    'php'
));

Using the constants doesn't even work, it's ignored:

$validator = new Zend\Validator\NotEmpty(array(
    Zend\Validator\NotEmpty::BOOLEAN,
    Zend\Validator\NotEmpty::PHP
));

Validation Manager doesnt recognize validator factory

Hi,

It seems using annotations is not possible to use custom validators defined through a factory.

/**
 * User
 * 
 * @ORM\Entity
 * @ORM\Table(name="user", indexes={
 *      @ORM\Index(name="group_id", columns={"group_id"}),
 *      @ORM\Index(name="full_name", columns={"first_name", "last_name"}),
 *      @ORM\Index(name="location_id", columns={"location_id"}),
 *      @ORM\Index(name="created_id", columns={"created_id"}),
 *      @ORM\Index(name="updated_id", columns={"updated_id"}),
 *      @ORM\Index(name="group_id", columns={"group_id"}),
 *      @ORM\Index(name="status", columns={"status"})
 *      },
 *      uniqueConstraints={@ORM\UniqueConstraint(name="email", columns={"email"})}
 * )
 * @ORM\Entity(repositoryClass="Crm\Repository\UserRepository")
 * @ORM\EntityListeners({"Crm\Entity\Listener\CreatedUpdatedListener"})
 */
class User
{

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false, options={"unsigned"=true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * 
     * @Annotation\Exclude
     */
    protected $id;

.....

    /**
     * @var string
     *
     * //@Annotation\Type("email")
     * @Annotation\Type("Crm\Form\Element\Email")
     * @Annotation\Required(true)
     * @Annotation\Filter({"name":"Zend\Filter\StringTrim"})
     * @Annotation\Filter({"name":"Zend\Filter\StripTags"})
     * @Annotation\Validator({"name":"uniqueobject"})
     * @Annotation\Options({"label":"Email", "column-size":"sm-10", "label_attributes":{"class":"col-sm-2"}})
     * @Annotation\Flags({"priority": 93})
     * 
     * @ORM\Column(name="email", type="string", length=128, nullable=false)
     */
    protected $email;


}

And no matter where I place the factory into module_config it doesnt get called...

    'validators' => array(
        'factories' => array(
            'uniqueobject' => function ($sm){
                die('request validator');
                $uniqueObject = new Crm\Validator\UniqueObject(array(
                    'fields' => 'email',
                    'object_repository' => 'Crm\Entity\User',
                    'object_manager' => 'Doctrine\ORM\EntityManager',
                    'service_locator' => $sm
                ));
                return $uniqueObject;
            },
        ),
    ),
    'form_element_manager' => array(
        'factories' => array(
            'uniqueobject' => function ($sm){
                die('request validator');
                $uniqueObject = new Crm\Validator\UniqueObject(array(
                    'fields' => 'email',
                    'object_repository' => 'Crm\Entity\User',
                    'object_manager' => 'Doctrine\ORM\EntityManager',
                    'service_locator' => $sm
                ));
                return $uniqueObject;
            },
        ),
    ),

The error is:

Zend\Validator\ValidatorPluginManager::get was unable to fetch or create an instance for uniqueobject

Check All Headers In Documentation

Check headers are correct

TLDR; Headers should use the #, ## etc to format different levels of headers, and not be underlines using ===== or ``-----`, or be psuedo header using bold

Check all headers on the documentation - headers should use the hash style of declaration rather then be underlined with equals or dashes. The more hashes, the more of a subheading. Eg:

  • # is equal to <h1>
  • ## is equal to <h2>
  • ### is equal to <h3>
  • #### is equal to <h4>
  • ##### is equal to <h5>

Headings should be appropriate for their level in the documentation.

Psuedo headers using bold tags ** should be replaced with appropriate level of heading tag.

What is the point of Zend\Validator\Translator\TranslatorInterface?

I am just trying to internationalize my Zend\Expressive application and stumbled upon the Zend\Validator\Translator\TranslatorInterface interface, which is checked when I use Zend\Validator\AbstractValidator::setDefaultTranslator() method. I learned now that I cannot use a normal Zend\I18n\Translator\Translator instance. In a Zend\Mvc scenario this issue is solved by the Zend\Mvc\I18n\Translator which uses an Zend\I18n\Translator\Translator instance and implements the Zend\Validator\Translator\TranslatorInterface interface.

It doesn't feel right to use the Zend\Mvc\I18n\Translator within my Zend\Expressive application.

It doesn't feel right to implement a Zend\Expressive\I18n\Translator similar to the Zend\Mvc\I18n\Translator.

What a mess.

So, what is the point of the Zend\Validator\Translator\TranslatorInterface in the first place? The Zend\I18n\Translator\TranslatorInterface has the same method signature for the translate() method except it adds another translatePlural() method to the interface. Why not split Zend\I18n\Translator\TranslatorInterface into two interfaces and kick Zend\Validator\Translator\TranslatorInterface?

Are there any plans to tidy this up? Anyway what about the plans to make the validators stateless and extract the translation part from it? I think both is really needed for a ZF3 release to make translation and validation usable within a Zend\Expressive application.

URI Validator wrong validation

$validator = new Zend\Validator\Uri();
$uri = 'dss';
var_dump($validator->isValid($uri));

bool(true)

Why this is returning TRUE?

Documentation: PostCode is no longer a standard validation class

According to Standard Validation Classes, PostCode comes with the zend-validator distribution. While this appears to be correct for Zend 2.0, this is no longer the case in zend-validator 2.8. PostCode is now shipped in zend-i18n (which zend-validator merely suggests).

Had I not been away from Zend for a long time, this would probably have been obvious since the reference page for PostCode uses the right namespace prefix.

Note that the zend-i18n reference does not mention PostCode (in other words, the page should be moved, not just deleted).

[question] Why do the File\Extension validator validate the presence of a file?

Is it really the job of the File\Extension validator to check that the file exists? Especially given that there already is a File\Exists validator.

I'm trying to write some tests for a class which inherits File\Extension, but the fact that the validator checks that the file exists makes it harder than I think it should be.

My problem is with these lines:

    // Is file readable ?
    if (empty($file) || false === stream_resolve_include_path($file)) {
        $this->error(self::NOT_FOUND);
        return false;
    }

A related question is why File\Extension uses stream_resolve_include_path instead of is_readable to check that the file exists. I can't think of a use case where you'd want to look in the include paths. To me it looks borderline security related, even though I can't think of a concrete threat right now.

error on documentation example code

The section "Using pre-translated validation messages" on the Zend Validator documentaion has the following example:

use Zend\I18n\Translator\Resources;
use Zend\Mvc\I18n\Translator;
use Zend\Validator\AbstractValidator;

$translator = new Zend\Mvc\I18n\Translator();
$translator->addTranslationFilePattern(
    'phpArray',
    Resources::getBasePath(),
    Resources::getPatternForValidator()
);
AbstractValidator::setDefaultTranslator($translator);

Fist Zend\Mvc\I18n\Translator(); needs an I18nTranslatorInterface and that's not documented on this example.

The another problem with this example is that it throws this Exception:

A plugin by the name "phpArray" was not found in the plugin manager Zend\I18n\Translator\LoaderPluginManager

Because the alias for Zend\I18n\Translator\Loader\PhpArray now is "phparray" not "phpArray"

[NotEmpty] validator strange behavior with boolean values

I have json like this:

{
    "name": "some name",
    "enabled": false
} 

And now I want to validate if enabled field is not empty.

$validator = new NotEmpty();
$this->assertTrue($validator->isValid(false)); // fails
$validator->setType(NotEmpty::BOOLEAN);
$this->assertTrue($validator->isValid(false)); // fails, what? why? How can I check boolean values?

false it is for sure valid boolean value how this can be considered empty? and even when I set type to boolean this doesn't matter it is still empty.

Even more strange this is in tests also

[false, false],

Maybe I don't know something and someone can explain reason behind this?

Hostname::isValid() ip address detection is detecting false positive

Hey,

I investigated an issue I had. An E-Mail-Address is recognized as invalid. To guard the real email address, I create something that is fitting to my detected issue.
Lets use the email address '[email protected]'.

If I try to validate this host name, I get an error from Hostname::IP_ADDRESS_NOT_ALLOWED.
Why? Because of the used regexp.

    public function isValid($value)
    {
        if (!is_string($value)) {
            $this->error(self::INVALID);
            return false;
        }

        $this->setValue($value);
        // Check input against IP address schema
        if (preg_match('/^[0-9a-f:.]*$/i', $value)
        //....

The regexp '/^[0-9a-f:.]*$/i' expressed as sentence would be something like:
This matches if provided value contains only numbers from "0" to "9", characters from "a" to "f", ":" and ".".
Since my example domain only exists out of numbers and characters from "a" to "f", this expression would match false positive.
Is there a chance to fix this?
Since my client is using php 5.4, I would need a new zend framework version also for that.

Thanks in advanced.

AbstractDb - Exclude Parameter - Bug

Abstract Class Zend\Validator\Db\AbstractDb;

The function getSelect has a bug when you the exclude parameter contains a Zend\Db\Sql\Where parameter

if ($this->exclude !== null) {
            if (is_array($this->exclude)) {
                $select->where->notEqualTo(
                    $this->exclude['field'],
                    $this->exclude['value']
                );
            } else {
-->>>                $select->where($this->exclude);
            }
        }

The problem is that $select->where($this->exclude) will overwrite the entire WHERE clause
defined just above

$select          = new Select();
        $tableIdentifier = new TableIdentifier($this->table, $this->schema);
        $select->from($tableIdentifier)->columns([$this->field]);
        $select->where->equalTo($this->field, null);

The workaround is when you pass a WHERE inside the exclude you have to repeat

equalTo($this->field, null);

The fix would be to use

if($this->exclude instanceof Where){
 $select->where->addPredicate($this->exclude);
} else {
 $select->where($this->exclude);
}

Thank you

Unexpected behaviour with Identical validator

I've come across a case where the Identical validator isn't working as expected.

I've got two inputs in a fieldset "email" and "emailConfirmation". Both have the same filters in the input filter specification, one of which is the StringToLower filter. When doing the identical comparison the first field "email" has all filters applied but the token "emailConfirmation" has no filters applied and seems to be the raw input from the form. This means I'm getting a false negative match when there is some capitalisation in the raw input even though both fields were identical when the form was submitted.

A good example where this scenario is problematic is when inputting data via a mobile phone, often the first letter of input is capitalised by default.

Is there any way to make sure all filters are applied to the token before running the comparison or that the identical comparison is run on raw input for both elements rather than any filters being applied to just one element? Both would seem better than the current behaviour.

Require zend-math

This module requires zend-math to work (e.g. for Validate\Csrf) so there should be a dependency in package.json.

[ZF3] Use PHP native validators?

Hi everyone,

As part of the upcoming refactor to ZF3 validator, I think we should discuss if we maintain our own implementation for some validators, or use the built-in validators included in PHP (http://php.net/manual/en/filter.filters.validate.php).

For the pros:

  • Less work on our side and things to maintain, especially for maintenance
  • Better performance as those complex validators
  • Some validators have more options

For the cons:

  • I know that some validators used to have some bug... but it was long time ago and maybe those have been fixed long time ago, especially as we set dependency to 5.5 now
  • Some validators have less options

The impacted validators are:

idn_to_utf8: empty domain name in EmailAddress Validator

idn_to_utf8(): idn_to_utf8: empty domain name in ...\vendor\zendframework\zend-validator\src\EmailAddress.php on line 557
When a field has EmailAddress validator and its value is empty, this warning shows up.
The fields validator has required=true and also NotEmpty validator.
shouldn't a empty value considered false validation and return false before checking for domain name ?

Zend 2.5.1
php 5.6.16

Unconventional behavior in EmailAddress validator

Configuring a 'message' option on validators should return that single message on failure. (ref http://framework.zend.com/manual/current/en/modules/zend.validator.messages.html)

The second parameter defines the failure which will be overridden. When you omit this parameter, then the given message will be set for all possible failures of this validator.

I have a simple field in a sign up form whose counterpart InputFilter contains this configuration:

'validators' => [
                [
                    'name' => EmailAddress::class,
                    'options' => [
                        'useMxCheck'        => true,
                        'useDeepMxCheck'    => true,
                        'useDomainCheck'    => true,
                        'message'           => _( "Hey bud, check your email." ),
                    ],
                ],

In this case, unfortunately, we get a regex failure that's pretty cryptic on top of what we've set.

The input does not match against pattern '/^[a-zA-Z0-9.!#$%&'+/=?^`{|}~-]+@[a-zA-Z0-9-]+(?:.[a-zA-Z0-9-]+)_$/'

The message configured should preempt the regex failure.

ZF2 fix #6725

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/6736
User: @Qronicle
Created On: 2014-10-06T13:07:21Z
Updated At: 2015-02-19T19:55:15Z
Body


Comment

User: @Ocramius
Created On: 2014-12-24T00:47:53Z
Updated At: 2014-12-24T00:47:53Z
Body
Linking #6725


Comment

User: @Ocramius
Created On: 2014-12-24T00:49:15Z
Updated At: 2014-12-24T00:49:15Z
Body
More tests specific to #6725 are required here.


Comment

User: @weierophinney
Created On: 2015-02-19T19:55:15Z
Updated At: 2015-02-19T19:55:15Z
Body
@Qronicle ping... we need unit tests before we can merge.


Check For Blockquotes In Docs

Check the document for bad blockquoutes

TLDR; Check blockquotes are formatted correctly using > and check headings in blockquotes are using ###

Blockquotes are donated by a single greater than character and then a space. Make sure all the blockquotes in every doc file are correctly formatted. Headings in blockquotes should use ### and not bold.

Any paragraph spacing in blockquotes should be marked using a single greater than, then a space.

Check Documentation Tables

Check the tables in a document

TLDR; All tables should be in the format of GHFM using | and - as horizontal and vertical separators respectively

Check all tables are in the correct format. Please don't use leading and trailing | - more information on github flavoured markdown tables can be found here.

Email validator hostname check for not empty

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7138
User: @freax
Created On: 2015-01-19T20:16:40Z
Updated At: 2015-01-25T01:39:34Z
Body
Sometimes there is a warning because of empty hostname parameter in checkdnsrr function.


Comment

User: @Ocramius
Created On: 2015-01-19T20:19:26Z
Updated At: 2015-01-19T20:19:26Z
Body
@freax please rebase and provide a test case for the hostname affected by this bug.


Comment

User: @DASPRiD
Created On: 2015-01-19T20:53:17Z
Updated At: 2015-01-19T20:54:58Z
Body
@Ocramius adding a hostname to the test suite which could fail any time? Sounds like a bad idea.


Comment

User: @Ocramius
Created On: 2015-01-19T22:40:55Z
Updated At: 2015-01-19T22:40:55Z
Body
I mean that data-providers need to be adjusted ;-)
On Jan 19, 2015 9:53 PM, "Ben Scholzen" [email protected] wrote:

@Ocramius https://github.com/Ocramius adding a hostname to the test
suit which could fail any time? Sounds like a bad idea.


Reply to this email directly or view it on GitHub
zendframework/zendframework#7138 (comment).


Comment

User: @freax
Created On: 2015-01-20T17:12:07Z
Updated At: 2015-01-20T17:12:07Z
Body
I don't think this PR needs a test case, because it's nothing to break actually.
This condition fails if hostname will be empty anyway, but this PR provides no more thipple warning in this case.
I got this warnings twise and I can't reproduce it.
Actually, I think it's a pretty rare case when script can't get MX-record for hostname.


Comment

User: @Ocramius
Created On: 2015-01-25T01:39:34Z
Updated At: 2015-01-25T01:39:34Z
Body

I don't think this PR needs a test case, because it's nothing to break actually.

code changes affecting branching of execution paths always require testing, regardless of the impact they have.

This condition fails if hostname will be empty anyway, but this PR provides no more thipple warning in this case.

And your test should actually try to reproduce the warning instead: reaching the point where you can reproduce the warning will also give you a better understanding the problem.

Actually, I think it's a pretty rare case when script can't get MX-record for hostname.

You can inject a fake hostname validator to get to that.


Check Documentation For Other Things

Check docs for other problems

TLDR; Cast your eye over the documetation for any problems not covered in the other issues

Things slip through the net, so check the documentation for other problems that have been missed. Common other problems include

  • Bullet lists (should be single * then space at the start of line)
  • Inline code - should be marked by three backticks at start and finish
  • bookdown.json file is correctly formated and has the right escaping
  • Links between documentation using RST have been stripped
  • Any other RST has been removed correctly
  • Anything and everything not covered

If you end up fixing the same problem over and over, please ping Gary Hockin - we may be able to add bespoke issue for that problem, or fix in automated capacity

Road to ZF3

Hi,

I've done a massive PR to this (zendframework/zendframework#5067) but it's a massive work and a big hell to review.

I suggest that we:

  1. Move validators to their specifc components (for instance moving Db validators to the Zend\Db component), and deprecating the validators here (for version 2.5).
  2. Remove them in v3, and start the refactoring work. Here are various things I have done in the past:
  • Make validators stateless (each validator returns a ValidationResult, that can be translated using another component for instance).
  • Using the new service manager of ZF3.
  • Homogeneize names (in ZF2, we didn't have time to use the "underscore_separated" convention for option name, which make it very incoherent with how the framework work).
  • Various code cleaning, optimization for PHP 5.5

Refactor ValidatorChainTest

ZendTest\Validator\ValidatorChainTest has many tests are out of the scope of ValidatorChain these tests must be moved or removed.

Examples:

  • testStaticFactoryClassNotFound
  • testIsValidWithParameters
  • testSetGetMessageLengthLimitation
  • testSetGetDefaultTranslator

Cannot install dependencies via composer

If I try to run composer install on the package I get the following errors:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - zendframework/zend-http 2.5.4 requires zendframework/zend-validator ^2.5 -> satisfiable by zendframework/zend-validator[2.5.0, 2.5.1, 2.5.2, 2.5.3, 2.5.4, 2.6.0, 2.7.0, 2.7.1, 2.7.2, 2.7.3, 2.8.0, 2.9.x-dev, 2.8.x-dev].
    - zendframework/zend-http 2.6.x-dev requires zendframework/zend-validator ^2.5 -> satisfiable by zendframework/zend-validator[2.5.0, 2.5.1, 2.5.2, 2.5.3, 2.5.4, 2.6.0, 2.7.0, 2.7.1, 2.7.2, 2.7.3, 2.8.0, 2.9.x-dev, 2.8.x-dev].
    - zendframework/zend-http 2.5.x-dev requires zendframework/zend-validator ^2.5 -> satisfiable by zendframework/zend-validator[2.5.0, 2.5.1, 2.5.2, 2.5.3, 2.5.4, 2.6.0, 2.7.0, 2.7.1, 2.7.2, 2.7.3, 2.8.0, 2.9.x-dev, 2.8.x-dev].
    - Can only install one of: zendframework/zend-validator[2.5.1, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.5.2, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.5.3, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.5.4, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.6.0, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.7.0, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.7.1, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.7.2, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.7.3, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.8.0, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.9.x-dev, No version set (parsed as 1.0.0)].
    - Can only install one of: zendframework/zend-validator[2.8.x-dev, No version set (parsed as 1.0.0)].
    - zendframework/zend-validator 2.5.0 requires zendframework/zend-stdlib ~2.5.0 -> satisfiable by zendframework/zend-stdlib[2.5.0, 2.5.1, 2.5.2] but these conflict with your requirements or minimum-stability.
    - Installation request for zendframework/zend-validator No version set (parsed as 1.0.0) -> satisfiable by zendframework/zend-validator[No version set (parsed as 1.0.0)].
    - Installation request for zendframework/zend-http ^2.5.4 -> satisfiable by zendframework/zend-http[2.5.4, 2.6.x-dev, 2.5.x-dev].

Abstract validator creates warning when an array value contains circular reference

As the \Zend\Validator\AbstractValidator::createMessage method uses var_export to convert arrays to strings this fails if the array contains a circular reference. The problem line is https://github.com/zendframework/zend-validator/blob/master/src/AbstractValidator.php#L294.

I've provided a quick example of this below which outputs "PHP Warning: var_export does not handle circular references":

class ExampleValidator extends \Zend\Validator\AbstractValidator
{
    protected $messageTemplates = [
        'someError' => 'error'
    ];
    public function isValid($value)
    {
        $this->setValue($value);
        $this->error('someError');
        return false;
    }
}

class Circular {
    public $reference;
}

$test = new Circular();
$test->reference = $test;

$validator = new ExampleValidator();
$validator->isValid([$test]);

Date::convertString() - return a more appropriate message for non-existent date.

For example, for input date of '2016-02-31', the error message of FALSEFORMAT - "The input does not fit the date format Y-m-d" is included in the return, which is not very descriptive, even a bit misleading.

The actual 'warnings' message from DateTime::getLastErrors() is "The parsed date was invalid".

Proposal:

  • Add const NONEXISTENT = 'dateNonExistent';
  • In $messageTemplates, add self::NONEXISTENT => "The date does not exist"; or self::NONEXISTENT => "No such day in calendar";
  • In convertString(), use $this->error(self::NONEXISTENT); instead of $this->error(self::FALSEFORMAT);

injectTranslator is called to early

In Line 141 of /src/ValidatorPluginManager.php a new Initializer is added by the line:

    $this->addInitializer([$this, 'injectTranslator']);

after parent::__construct() is called. Which means, that on creation of a new validator the method `injectTranslator()' is called before the closure:

    $this->addInitializer(function ($instance) use ($self) {
        if ($instance instanceof ServiceLocatorAwareInterface) {
            $instance->setServiceLocator($self);
        }
    });

of the AbstractPluginManager is called.

But since the injectTranslator method needs the serviceLocator and the serviceLocator isn't injected at this point of time, the result of $this->getServiceLocator() in injectTranslator will always be null. And that's why there will be never a translator injected.

ZF1 Notice: Array to string conversion in Zend/Filter/StringTrim.php on line 99

( ! ) Notice: Array to string conversion in /var/www/games/library/Zend/Filter/StringTrim.php on line 99
Call Stack

Time Memory Function Location

1 0.0009 236576 {main}( ) ../index.php:0
2 0.0448 1511056 Zend_Application->run( ) ../index.php:50
3 0.0448 1511176 Zend_Application_Bootstrap_Bootstrap->run( ) ../Application.php:384
4 0.0450 1512240 Zend_Controller_Front->dispatch( ) ../Bootstrap.php:105
5 0.0560 1707232 Zend_Controller_Dispatcher_Standard->dispatch( ) ../Front.php:954
6 0.0590 1826648 Zend_Controller_Action->dispatch( ) ../Standard.php:308
7 0.0709 2692416 Zend_Controller_Action_HelperBroker->notifyPostDispatch( ) ../Action.php:527
8 0.0710 2693464 Zend_Controller_Action_Helper_ViewRenderer->postDispatch( ) ../HelperBroker.php:277
9 0.0710 2693752 Zend_Controller_Action_Helper_ViewRenderer->render( ) ../ViewRenderer.php:972
10 0.0758 2694784 Zend_Controller_Action_Helper_ViewRenderer->renderScript( ) ../ViewRenderer.php:933
11 0.0758 2694912 Zend_View_Abstract->render( ) ../ViewRenderer.php:912
12 0.0759 2711840 Zend_View->_run( ) ../Abstract.php:888
13 0.0759 2712352 include( '..../application/views/scripts/user/login.phtml' ) ../View.php:157
14 0.0763 2720976 Zend_Form->__toString( ) ../View.php:3
15 0.0763 2721072 Zend_Form->render( ) ../Form.php:3010
16 0.0767 2738264 Zend_Form_Decorator_FormElements->render( ) ../Form.php:2994
17 0.0769 2740616 Zend_Form_Element->render( ) ../FormElements.php:116
18 0.0776 2771608 Zend_Form_Decorator_ViewHelper->render( ) ../Element.php:2071
19 0.0777 2772208 Zend_Form_Decorator_ViewHelper->getValue( ) ../ViewHelper.php:236
20 0.0777 2772208 Zend_Form_Element->getValue( ) ../ViewHelper.php:206
21 0.0777 2772512 Zend_Form_Element->_filterValue( ) ../Element.php:610
22 0.0777 2773264 Zend_Filter_StringTrim->filter( ) ../Element.php:594

File/Count validator does not work

Validation result always false. Warning dropped

Warning: dirname() expects parameter 1 to be string, array given in /home/autowp/autowp.ru/vendor/zendframework/zend-validator/src/File/Count.php on line 209

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" />
</form>
$form = new \Zend\Form\Form(null);
$form->add([
    'name' => 'file',
    'type' => 'File'
]);

$inputFilter = new \Zend\InputFilter\InputFilter();
$inputFilter->add([
    'validators' => [
        [
            'name'    => \Zend\Validator\File\Count::class,
            'options' => ['min' => 1]
        ]
    ]
], 'file');

$form->setInputFilter($inputFilter);

$form->setData($this->getRequest()->getFiles());
print $form->isValid() ? 'valid' : 'invalid'; // invalid, warning dropped

[ZF3] Rename all validators

Hi,

As part of the upcoming refactor, I'm suggesting to rename all validators to append "Validator" to their name. This make this more homogeneous with otehr part where we usually append a name. This also solve a common name clash where you are using both a Filter and Validator, but that have the same name (Int and Int,Float and Float), hence forcing to define a namespace alias.

What do you think? :)

ping @weierophinney @Maks3w

Increase Test Coverage

Test coverage is at 47% and could be a lot higher. Will submit a pull request to increase test coverage.

ImageSize and Size Validator behave unexpected in windows with PHP 5.4+

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7650
User: @razonklnbd
Created On: 2015-12-06T03:12:39Z
Updated At: 2016-02-13T15:33:25Z
Body
Environment -
OS: Windows 10
PHP: 5.4+ [I tested in 5.4, 5.6 & 7.0]
ZF: 2.4.9

Recreate -

  • create any HTML form to accept at least one image
  • apply validator on size and image size
  • submit form through http request

Reason -
at Zend\Validator\File\ImageSize and Zend\Validator\File\Size class isValid method return false due to using "stream_resolve_include_path" function. In my system it only resolves for include paths relative path document. You can locate exactly at line 354 of Zend\Validator\File\ImageSize class


Domainkey: Underscore in hostname

default._domainkey.example.com

$regexChars = [0 =&gt; '/^[a-z0-9\x2d]{1,63}$/i'];

[hostnameInvalidHostnameSchema]: The input appears to be a DNS hostname but cannot match against hostname schema for TLD 'COM'
[hostnameInvalidLocalName]: The input does not appear to be a valid local network name

[WIP] [ZF3] Validators refactoring

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/5067
User: @bakura10
Created On: 2013-09-03T14:43:59Z
Updated At: 2014-09-28T00:34:50Z
Body
Hi everyone,

Again another PR/issue for ZF3. I promise, this is the last one I will make (ok, maybe Forms too :D...).

This one is another lower-level component, but I need this one to correctly finish the InputFilter one.

As for filter, the main changes will be: some performance optimizations we can make with PHP 5.4, cleaning some code, homogenize options by using underscore_separated... The only real change I've made for now is to make the ValidatorChain exactly the same as FilterChain (I was always bothered that those classes didn't have the same method names or underlying implementation).

HOWEVER, there is a change @Ocramius and I discussed on IRC and I'd love to have your opinion on that. The InputFilter refactor made the component completely stateless. It opened interesting optimizations, and the idea came to make validators also stateless.

To stay simple, the following code:

$validator = new Boolean();
if ($validator->isValid(true)) {
   // Do something
} else {
  $error = $validator->getErrorMessages();
}

Will be transformed to:

$validator = new Boolean();
$validationResult = $validator->validate($value);

if ($validationResult->isValid()) {
   // Do something
} else {
   $error = $validationResult->getErrorMessages();
}

As for input filters, validationResult instances are serializable and can be transformed to JSON.

Translation would still be handled by the validators themselves: they will translate the error messages and pass them to the validation result.

What do you think of this idea? Is there any drawback that you may see from it?

EDIT : Credit for the idea to George (https://gist.github.com/texdc/5929229#file-validationresultinterface-php)


Comment

User: @Ocramius
Created On: 2013-09-03T16:41:29Z
Updated At: 2013-09-03T16:47:17Z
Body
Note: as discussed on IRC (if you are reading this and are not on IRC, then the question is why you aren't!), translations can be handled in a very different way.

Having the translator within the validation component is quite problematic, so what we can do is having an error translator that works like following:

$validationTranslator = new ValidationTranslator(new Translator(/*...*/));
$validator = new Boolean();
$validationResult = $validator->validate($value);

if ($validationResult->isValid()) {
    // Do something
} else {
    $translatedResult = $validationTranslator->translate($validationResult);
    // pseudo - could also have a different API from the one in ValidationResult
    $error = $translatedResult->getErrorMessages();
}

Look ma! Validators don't know about translations anymore!

Eventually, a ValidationResult may implement logic to ease access to patterns or context variables needed by the translator. That interface doesn't necessarily cause a dependency to the I18n component.


Comment

User: @bakura10
Created On: 2013-09-03T16:48:16Z
Updated At: 2013-09-03T16:48:16Z
Body
That's pure genius.


Comment

User: @bakura10
Created On: 2013-09-05T16:59:04Z
Updated At: 2013-09-05T16:59:04Z
Body
ping @Ocramius and @weierophinney

I've made a proof of concept with the Between validator. There are multiple things I've made that we need to talk about.

  • First, the AbstractValidator is now very lightweight compared to previously. It has no reference to any Translator, no data to store. I've also removed the static "minimumLength" variable because I think it's the job of a view helper to cut a message.
  • Validators are completely decoupled from translation layer.
  • All variables were changed from camelCased to underscore_separated as it is by convention.
  • Please note the "setOptions" thing. This pattern goes beyond the Validator class. A LOT of classes inside a framework needs that kind of thing (an option array). I think that we can make it really convenient in ZF3 by writing a trait (like my previous PR @weierophinney :)) that could be used in all those classes. Of course, this trait would make some assumptions : that keys are underscore_separated, and that the setter of the corresponding property is called to set the value (this thing should propably take into account isser and has, until we have real property accessors in PHP :(). Of course, custom needs can avoid the use of the trait, but I think that would be a convenient pattern if we really follow the same covnentions accross the framework. We could even write an interface like "OptionsCapableInterface, that a factory could check and inject options.
  • The validator classes are no longer responsible to create error messages. They just create a ValidationResult object with error messages, data and optional variables that can be injected inside the message.
  • The Validation error have three main methods: isValid, getRawErrorMessages and getErrorMessages. When getErrorMessages is called, variables are being replaced using a preg_replace. The getRawErrorMessages can be used by for translation. For instance, as @Ocramius said, we could create, in the translation component, a kind of decorator:
class ValidationResultTranslater
{
    public function getTranslatedErrorMessages(ValidationResultInterface $interface)
    {
        // do things
    }
}

Or, if we want to keep it simple, the dependency to i18n could be moved to the ValidationResult (which is probably better, as some people may be angry if we introduce anothr abstraction level).

What do you think of this?


Comment

User: @bakura10
Created On: 2013-09-05T17:03:35Z
Updated At: 2013-09-05T17:03:35Z
Body
Some more additional notes: now, the message variables are defined like this:

protected $messageVariables = array('min');

It is assumed that the validator has a property called "min". Still abut convention, we need to know if, in a message template, we prefer this:

protected $messageTemplates = array(
    self::KEY => 'An error occured "%my_variable%"
)

OR:

protected $messageTemplates = array(
    self::KEY => 'An error occured "%myVariable%"
)

I'd argue that it makes more sense to use camelCased in string.


Comment

User: @Ocramius
Created On: 2013-09-05T17:10:38Z
Updated At: 2013-09-05T17:10:38Z
Body
@bakura10 as long as it goes along what is defined in $messageVariables this shouldn't really matter...


Comment

User: @bakura10
Created On: 2013-09-05T17:17:27Z
Updated At: 2013-09-05T17:17:27Z
Body
Well. Yes it does, because we should follow the convention that options are underscore_separated. So in your validator classes, you will have:

protected $messageVariables = array('my_variable');

If we want adopt a differnt convention that may make more sense in the message, we need to inflect the value.


Comment

User: @weierophinney
Created On: 2013-09-06T14:24:19Z
Updated At: 2013-09-06T14:24:19Z
Body
@bakura10 This is looking great!

I'd argue we wouldn't need any i18n awareness in Validator after this. It would be up to the developer and/or a view helper to take the ValidationResult and use the data it contains to create translated messages. This approach would offer a cleaner separation of concerns. Since you already define the ability to get the messages as well as the message variables, this should be trivial to accomplish.


Comment

User: @bakura10
Created On: 2013-09-06T14:58:55Z
Updated At: 2013-09-06T14:58:55Z
Body
Thanks.

The only thing that bother me currently is how to handle the specific case of ValidatorChain. How should the ValidationResult be used? Because, by definition, the validator chain may return multiple error messages per validators, and multiple set of variables. If have no idea about how to do it.

Should we have a specific ValidationResult (ValidationResultCollection) or other way using nested arrays?


Comment

User: @weierophinney
Created On: 2013-09-06T20:54:03Z
Updated At: 2013-09-06T20:54:03Z
Body
@bakura10 I would argue having a ValidationResult and a ValidationResultCollection, which aggregates named ValidationResult and ValidationResultCollection instances; they should share a common interface that defines things like isValid() so that the developer can determine whether or not anything further needs to be done.

This allows developers to find the correctly named result in order to display individual validation messages, and also allows arbitrary nesting.


Comment

User: @bakura10
Created On: 2013-09-06T20:57:18Z
Updated At: 2013-09-06T20:57:18Z
Body
Ok. I'll do that then. Now, I need to also think about how to use them in other context (I think about input filters here). Remember that now InputFilter also have InputFilterResult classes, we need to know how everything would work together (currently, I extracted the error messages directly from the validators).

Anyway, I think it will be clearer once we start merging some refactored components, it's a bit hard for me to work with different branches like taht.


Comment

User: @texdc
Created On: 2013-10-04T00:10:10Z
Updated At: 2013-10-04T00:12:52Z
Body
Hmm, wasn't I the one who originally proposed this change?

https://gist.github.com/texdc/5929229#file-validationresultinterface-php


Comment

User: @bakura10
Created On: 2013-10-04T09:25:19Z
Updated At: 2013-10-04T09:25:19Z
Body
Yes @texdc . Although this one is only for the Validator component. You submitted it for InputFilter component (and I implemented it this way in the Input filter too).


Comment

User: @texdc
Created On: 2013-10-04T13:06:40Z
Updated At: 2013-10-04T13:06:40Z
Body
While I'm glad to see this implemented, you ripped the proposal straight from my gist. Credit where credit is due.

On Oct 4, 2013, at 4:25 AM, Michaël Gallego [email protected] wrote:

Yes @texdc . Although this one is only for the Validator component. You submitted it for InputFilter component (and I implemented it this way in the Input filter too).


Reply to this email directly or view it on GitHub.


Comment

User: @bakura10
Created On: 2013-10-04T13:09:10Z
Updated At: 2013-10-04T13:09:10Z
Body
Updated the description. Happy ? =)


Comment

User: @texdc
Created On: 2013-10-04T17:42:34Z
Updated At: 2013-10-04T17:42:34Z
Body
@bakura10 merci, c'est bien tout


Comment

User: @Thinkscape
Created On: 2013-10-05T18:29:50Z
Updated At: 2013-10-05T18:29:50Z
Body
I'd also add this for BC:

class AbstractValidator {
    public function isValid($value){
        return $this->validate($value)->isValid();
    }

    // [...]
}

Comment

User: @bakura10
Created On: 2013-10-05T18:33:05Z
Updated At: 2013-10-05T18:33:05Z
Body
As it is for ZF3 we don't care about BC @Thinkscape :).


Comment

User: @Thinkscape
Created On: 2013-10-05T21:25:24Z
Updated At: 2013-10-05T21:25:24Z
Body
Let me rephrase: . ease . of . use.

It's another one in a long list of "enhancements" that promote code culture but reduce usability, so that's the least we could do (in this particular case).


Comment

User: @bakura10
Created On: 2013-10-05T21:28:20Z
Updated At: 2013-10-05T21:28:20Z
Body
I'm not "against" that that much. The only problem with this approach is as because validators are now completely stateless, I suppose people still using that (just to avoid typing "validate($value)") will try to use this as it was before by fetching messages ($validator->getMessages()), while this obviosuly won't work, as error messages are now wrap in a simple, serializable ValidationResult object.

In fact, most of the time when dealing with validators, I think we also want the error messages, so it makes this shortcut lless useful and somewhat confusing, I think.


Comment

User: @Thinkscape
Created On: 2013-10-05T22:19:00Z
Updated At: 2013-10-05T22:19:00Z
Body
Point taken. It's ugly complex though :-\

Maybe we should take some time now and draft the whole process with a gist or two. I'd like to see the whole use case, from an array of data up to a view script displaying the message...


Comment

User: @bakura10
Created On: 2013-10-05T22:24:43Z
Updated At: 2013-10-05T22:26:11Z
Body
Well it's not that more complex and it allows us a lot of code simplifications (specifically regarding translations). I've done the same thing in the Input Filter refactor. Basically, it works like this:

$validator = new BooleanValidator();
$result     = $validator->validate($value); // value is not stored in validator so it can be reused directly again
$result2    = $validator->validate($anotherValue);

if ($result->isValid() && $result2->isValid()) {
    // Do something
} else {
    // as validators are now stateless, messages are stored in validation result, so you can
    // get both although we executed the validator twice
    $messages = array_merge($result->getErrorMessages(), $result2->getErrorMessages());
}

A nice thing of having this simple object is that it is now serializable and json serializable. So in a REST context, you could simply do that:

return json_encode($result); // will return the error messages

The dependency to translation layer is compeltely removed in validators (see discussion above), so we could think about a thin layer in translator:

$translate = $this->translator->translate($validationResult);

Not sure about the syntax yet.


Comment

User: @Thinkscape
Created On: 2013-10-06T08:29:03Z
Updated At: 2013-10-06T08:29:03Z
Body
Hmm... ok... how would you imagine specific errors propagating down to the translator helper ? How/when would interpolation be handled ? Would it work without translator out of the box? (as it currently does)


Comment

User: @bakura10
Created On: 2013-10-06T09:56:31Z
Updated At: 2013-10-06T09:56:31Z
Body
@Thinkscape , see this file: https://github.com/bakura10/zf2/blob/95af54febe08a2844f92738a94d0bd70db3af865/library/Zend/Validator/Result/ValidationResult.php

Interpolation is done on the ValidationResult itself, along the variables. This allow to translate error messages in multiple languages too (which is nearly impossible to do right now).

My only concern now is how to handle the specific case of ValidationChain to avoid conflicts in variables names.


Comment

User: @bakura10
Created On: 2013-10-06T12:22:06Z
Updated At: 2013-10-06T12:22:06Z
Body
@texdc : I've made some more work today: https://github.com/bakura10/zf2/blob/14dcdd175329f56f922e377eed7c3fc1c9d29e83/library/Zend/Validator/Result/ValidationResult.php#L124

So now for serialization, I save the data, message variables and raw error messages (to be able to recreate the object). On the other hand, for jsonSerializable, I just encode the error messages (because I think this is the most sane use case as this feature will mostly be used for REST I think).

@Thinkscape : I've written tests for the ValidationResult stuff. I think it should be clear about the usage: https://github.com/bakura10/zf2/blob/14dcdd175329f56f922e377eed7c3fc1c9d29e83/tests/ZendTest/Validator/Result/ValidationResultTest.php


Comment

User: @texdc
Created On: 2013-10-06T21:36:32Z
Updated At: 2013-10-06T21:36:32Z
Body
I think you're missing the point of a dedicated result class. It should be extremely light-weight to facilitate messaging. Adding data is out-of-scope and unnecessary because the data is available before validation. Message building should (still) be handled by the validator, not the result. The result should only contain ready-to-be-consumed messages.

public function validate($data)
{
    $result = $this->validator->validate($data);
    $this->eventManager->trigger(__METHOD__, $this, compact('data', 'result'));
    return $result;
}

Comment

User: @Ocramius
Created On: 2013-10-06T21:40:08Z
Updated At: 2013-10-06T21:40:32Z
Body
@texdc the result is just a value. Translating it happens somewhere in a Zend\I18n\Validator\Something.

It's an immutable packet of data containing all what is necessary to assemble relevant bits of sentences for validation errors (to me).

The submitted data can be part of the packet in my opinion...


Comment

User: @bakura10
Created On: 2013-10-06T21:40:28Z
Updated At: 2013-10-06T21:40:28Z
Body
Isn't that the case in my implementation? I agree that data may be removed from the ValidationResult (well, the problem is for people that would like to include the value inside the error message during interpolation).

However I don't agree with you on another point: the validator should not create the error messages itself and do the interpolation. Otherwise you miss the whole advantage of being able to separate i18n component from the validator. As the ValidationResult contains message variables AND raw error messages, a ValidationResultTransaltor can now be used to translate all the messages.


Comment

User: @texdc
Created On: 2013-10-06T21:42:06Z
Updated At: 2013-10-06T21:42:06Z
Body
@Ocramius right, but the data is not necessary and weighs the result down.

@bakura10 The value can be included in the messages when they're generated by the validator. If the validator doesn't generate messages then it should just return a boolean and let a message generator populate the result.


Comment

User: @bakura10
Created On: 2013-10-06T21:42:49Z
Updated At: 2013-10-06T21:42:49Z
Body
Having said this, I think it even makes sense to remove the data from ValidationResult (so we only stay with raw error message and message variables, the only thing that are needed to create error messages). What do you think @Ocramius ?


Comment

User: @bakura10
Created On: 2013-10-06T21:43:49Z
Updated At: 2013-10-06T21:43:49Z
Body
@texdc : so you're assuming the translation still happen in validator as it is now, while I saw the biggest advantage of this specific result class to allow complete separatin of concenrs.


Validator\Db\NoRecordExists with Select needs first where clause as the given field

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/7602
User: @YuriStruszczynski
Created On: 2015-07-02T09:18:48Z
Updated At: 2015-11-06T22:06:43Z
Body
//Check that the emailaddress for a given project is not present in the database
$select = new \Zend\Db\Sql\Select();
$select->columns(array('mail'))->from('candidates')->where(array('mail' => '', 'project_id' => $id));
$validator = new \Zend\Validator\Db\NoRecordExists($select);
$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
$validator->setAdapter($dbAdapter);
$inputFilter->get('mail')->getValidatorChain()->attach($validator);

This one works fine! But if you change to the next line, the fields will not be validated:
$select->columns(array('mail'))->from('candidates')->where(array('project_id' => $id, 'mail' => ''));

Because in AbstractDb.php the query() function overrides your first where parameter with the value of the connected field:
$parameters = $statement->getParameterContainer();
$parameters['where1'] = $value;

In my opinion this should be mentioned somewhere or be changed like this:

if ($this->select instanceof Select) {
$parameters = $statement->getParameterContainer();
$parameters['where1'] = $value;
}


Translations do not work with Zend\Mvc 3 anymore

I just stumbled upon an issue with Zend\Validator in combination with the Zend\Mvc 3 release. The 2.8.0 release is expecting a services called MvcTranslator to be injected as the translator for each validator.

https://github.com/zendframework/zend-validator/blob/master/src/ValidatorPluginManager.php#L446

But in Zend\Mvc 3 no service called MvcTranslator is defined anymore. This results into the fact that no validator messages are translated any more.

Date validator bug issue #6406

This issue has been moved from the zendframework repository as part of the bug migration program as outlined here - http://framework.zend.com/blog/2016-04-11-issue-closures.html


Original Issue: https://api.github.com/repos/zendframework/zendframework/issues/6407
User: @svycka
Created On: 2014-06-23T13:13:26Z
Updated At: 2015-11-12T09:47:03Z
Body


Comment

User: @ezimuel
Created On: 2014-08-06T16:03:56Z
Updated At: 2014-08-06T16:03:56Z
Body
@svycka what's the goal of this PR? I see only a change in the unit test. Can you explain, please? Thanks.


Comment

User: @Ocramius
Created On: 2014-08-06T16:05:28Z
Updated At: 2014-08-06T16:05:28Z
Body
The issue just shows the failure. It is just in form of a PR so that we:

  • get the tests to run
  • see the actual diff
  • can write a fix on top of that

Comment

User: @svycka
Created On: 2015-03-19T08:42:59Z
Updated At: 2015-03-19T08:42:59Z
Body
This PR shows this bug: zendframework/zendframework#6406

$validator = new \Zend\Validator\Date(array('locale' => 'en', 'format' => 'Y-m-d'));
$validator->isValid(123); // returns true

As @DASPRiD said this was intentionally desired. But I don't see why. also there was a PR zendframework/zendframework#6865 to fix it not for me to decide it was good or no.

@weierophinney what do you think?


Comment

User: @hoppithek
Created On: 2015-11-12T09:46:06Z
Updated At: 2015-11-12T09:47:03Z
Body
+1
totally agree that an interger time should not validate as a formatted date string. The suggested solution in #6406 to make accepted types configurable sounds OK, but I would consider this a bug from the beginning.


Let AbstractDb implement AdapterAwareInterface

At the moment Zend\Validator\Db\AbstractDb has a method setAdapter to set the database adapter. I think the canonical way of doing that would be to implement the Zend\Db\Adapter\AdapterAwareInterface's setDbAdapter() instead, maybe by using the Zend\Db\Adapter\AdapterAwareTrait.

Automatize update of valid TLDs

Actually Hostname validator depends of a regular execution of bin/update_hostname_validator.php for to host an up to date list of IANA TLDs

This should be automatized and even the list could be published in a different package for to allow more regular updates for LTS versions and newer.

Discussion: #2

l

l

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.