Giter Club home page Giter Club logo

laminas-validator's Introduction

laminas-validator

Build Status

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

laminas-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 laminas/laminas-validator

Documentation

Browse the documentation online at https://docs.laminas.dev/laminas-validator/

Support

laminas-validator's People

Contributors

akrabat avatar bakura10 avatar cgmartin avatar codisart avatar dasprid avatar dchusovitin avatar dragonbe avatar evandotpro avatar ezimuel avatar freeaqingme avatar froschdesign avatar ghostwriter avatar gsteel avatar koopzington avatar laminas-bot avatar maks3w avatar marc-mabe avatar michalbundyra avatar mikaelkael avatar mimmi20 avatar mwillbanks avatar ocramius avatar ralphschindler avatar renovate[bot] avatar samsonasik avatar sgehrig avatar thinkscape avatar thomasweidner 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

laminas-validator's Issues

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.


Originally posted by @stevleibelt at zendframework/zend-validator#57

How to reject e-mail addresses with UTF-8 characters in the local part?

zend-validator 2.9.0 used to reject e-mail addresses with utf-8 characters in the local part (e.g. å or ö). As of zend-validator 2.10.0, such e-mail addresses seem to be considered valid. We are using postmark to send e-mails, which throws an exception at such e-mail addresses. Is there a way to configure Zend\Validator\EmailAddress to reject these e-mail addresses?


Originally posted by @aimfeld at zendframework/zend-validator#224

Documentation for GpsPoint is missing

Feature Request

Q A
New Feature yes
RFC no
BC Break no

Summary

It seems like the Documentation for Laminas\Validator\GpsPoint is missing. I never knew that there is a validator for this. 🤯

Cannot correctly validate cyrillic (or any other UTF-8) characters in local part

Here is the usage of the validator in the form:

[
    "name" => "email",
    "required" => false,
    "validators" => [
        [
            "name" => "EmailAddress"
        ]
    ]
]

The problem occurs when the user enters an email with UTF-8 characters in the local part.
Here is an example: тест@example.com

While debugging, Zend\Validator\EmailAddress::validateLocalPart() returns (boolean) true, thus causing the input to be valid (but it isn't).

Afterwards, sending an e-mail is impossible, because тест@example.com gets into the e-mail headers and they become invalid.

I have investigated the problem and it turns out that $this->idnToAscii($this->localPart) in the Zend\Validator\EmailAddress::validateLocalPart() method is causing the problem. It converts all UTF-8 characters to ASCII and makes the preg_match. It returns true and voila - wrong validation.


Originally posted by @thexpand at zendframework/zend-validator#119

Error in function setMax from Zend\Validator\File\Size for values greater than 2G

If I'm using big values for the maximum limit, I have error on conversion in bytes.
In PHP, on a 32-bit system, the largest value that can be held in an INT is 2147483647. This is equal with 1.999999(and more digits) Gb.
I've tested the setMax with a greater value, like 8000M, but the tests can be made also with 2G.

The function setMax has a casting method to integer
$max = (int) $this->fromByteString($max);
This method will return a negative value because of the cast "(int)".

Example: setMax(7.81 GB) will have calculated max -204010947

The propose is to use "floor" casting like
$max = floor($this->fromByteString($max));

This bug is also presented in ZF3 package.

I'm giving you the example of usage of Size validator, from a getInputFilter() function. The value returned by the below call $this->getUploadMaxFilesize() is "8000M".

           $file = new FileInput('imagepath');
            $file->getValidatorChain()->attach(new UploadFile());
            if($this->getUploadMaxFilesize()) {
                $file->getValidatorChain()->attach(new Size(array('max' => $this->getUploadMaxFilesize())));
            }
            $file->getValidatorChain()->attach(new Extension(array(
                'extension' => $this->getUploadFileExtensions(),
                'case' => false,
                'messages' => array('fileExtensionFalse' => "Only " . implode("/", $this->getUploadFileExtensions()) . " extension are allowed. File '%value%' hasn't an allowed extension"),
            )));
            $file->getFilterChain()->attach(
                new RenameUpload([
                'target' => PUBLICDIR . $this->getUploadPath() . $this->getUploadFilePrefix(),
                'randomize' => true,
                'use_upload_name' => false,
                'use_upload_extension' => true,
                'overwrite' => false,
            ]));
            $inputFilter->add($file);

Originally posted by @BogMor at zendframework/zend-validator#199

Valid hostnames are consideres invalid with Umlaut and certain TLDs

I initially encountered this problem while using the email validator. However the real origin is the hostname validator.

A simple testscript let's you reproduce this issue. In the example code I'm using an made up hostname, however the real one of my client is built up in the same manner: an german umlaut in the hostname as well as one of the newer tlds. Due to data privacy the script doesn't use the real hostname of my client.

The only thing you need to do is to install zend-validator via composer, create a script with the following code an run it within your browser:

<?php
require_once ('vendor/autoload.php');

// email validator tests

$validator = new \Zend\Validator\EmailAddress();

// this should return "success", but does not: umlaut & new tld
if (false === $validator->isValid('info@täst.tools')) {
    echo'<pre>';print_r($validator->getMessages());echo'</pre>';
} else {
    echo 'success';
}

// new tld, but no umlaut -> works
if (false === $validator->isValid('[email protected]')) {
    echo'<pre>';print_r($validator->getMessages());echo'</pre>';
} else {
    echo 'success<br>';
}

// umlaut but "classic" tld -> works
if (false === $validator->isValid('info@täst.com')) {
    echo'<pre>';print_r($validator->getMessages());echo'</pre>';
} else {
    echo 'success<br>';
}


// hostname validator

$validator = new \Zend\Validator\Hostname();


// this should return "success", but does not: umlaut & new tld
if (false === $validator->isValid('täst.tools')) {
    echo'<pre>';print_r($validator->getMessages());echo'</pre>';
} else {
    echo 'success<br>';
}

// new tld, but no umlaut -> works
if (false === $validator->isValid('test.tools')) {
    echo'<pre>';print_r($validator->getMessages());echo'</pre>';
} else {
    echo 'success<br>';
}

// umlaut but "classic" tld -> works
if (false === $validator->isValid('täst.com')) {
    echo'<pre>';print_r($validator->getMessages());echo'</pre>';
} else {
    echo 'success<br>';
}

Basically the upper three test, test the email validator, while the three later ones directly test the hostname validator.

The output of the script looks like the following:

Array
(
    [emailAddressInvalidHostname] => 'xn--tst-qla.tools' is not a valid hostname for the email address
    [hostnameInvalidHostnameSchema] => The input appears to be a DNS hostname but cannot match against hostname schema for TLD 'TOOLS'
    [hostnameLocalNameNotAllowed] => The input appears to be a local network name but local network names are not allowed
)
success
success
Array
(
    [hostnameInvalidHostnameSchema] => The input appears to be a DNS hostname but cannot match against hostname schema for TLD 'TOOLS'
    [hostnameInvalidLocalName] => The input does not appear to be a valid local network name
)
success
success

The first and fourth tests fail. And this is the issue. These are completely valid hostnames. Which are by the way not local.

Does anyone know how to fix this? I'm not deeply into the hostname validator. Installed was version 2.10 of the validator component.

For the background: we've developed a credential database application, with different types of credential-types and so on. One of the types is email credential which respectively requires the email address. There we encountered this issue.


Originally posted by @alexsawallich at zendframework/zend-validator#234

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).


Originally posted by @RayFinney at zendframework/zend-validator#103

Missing support for emojis as valid punycode

Hi all,

I ran into an issue when trying to validate hostnames to which the punycode converts to an emoji. I noticed there is no regular expression to match this on any of the IDNs. Were emojis left out for a reason? or am I missing something, perhaps there is a way to add my own custom IDNs to the list? I did not any feature which allows me to do that either.

The hostname I'm trying to validate is xn--ht8h.somename.com

If this has been asked before, my apologies, I have searched all over the place for the last day or two. If someone could point in the direction to fix this, I would really appreciate it.

Thank you.


Originally posted by @caquillo07 at zendframework/zend-validator#229

Should Regex constructor parameter be mandatory?

I can obtain a Regex validator from the ValidatorPluginManager like so:

$validatorManager = $container->get('ValidatorManager');
$validator = $validatorManager->get('regex', ['pattern' => '/abcd/i']);

However, if I attempt to obtain a Regex validator without the options (to configure it later) I received a PHP Fatal error:

$validatorManager = $container->get('ValidatorManager');
$validator = $validatorManager->get('regex');
$validator->setPattern('/abcd/i');
PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function Zend\Validator\Regex::__construct(), 0 passed in <REDACTED>/vendor/zendframework/zend-servicemanager/src/Factory/InvokableFactory.php on line 30 and exactly 1 expected in <REDACTED>/vendor/zendframework/zend-validator/src/Regex.php:51
Stack trace:
#0 <REDACTED>/vendor/zendframework/zend-servicemanager/src/Factory/InvokableFactory.php(30): Zend\Validator\Regex->__construct()
#1 <REDACTED>/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(758): Zend\ServiceManager\Factory\InvokableFactory->__invoke(Object(Zend\ServiceManager\ServiceManager), 'Zend\\Validator\\...', NULL)
#2 <REDACTED>/vendor/zendframework/zend-servicemanager/src/Servic in <REDACTED>/vendor/zendframework/zend-validator/src/Regex.php on line 51

Both the approaches of passing options to the ValidatorPluginManager and configuring the validator after invocation work fine for all validators except Regex. From what I can tell, the Regex validator is the only one in the zendframework/zend-validator package where the constructor parameter is mandatory:

/**
 * Sets validator options
 *
 * @param  string|Traversable $pattern
 * @throws Exception\InvalidArgumentException On missing 'pattern' parameter
 */
public function __construct($pattern)
{
    // ...
}

For all the other validators the contructor parameters are optional, which is exactly how the AbstractValidator describes it:

/**
 * Abstract constructor for all validators
 * A validator should accept following parameters:
 *  - nothing f.e. Validator()
 *  - one or multiple scalar values f.e. Validator($first, $second, $third)
 *  - an array f.e. Validator(array($first => 'first', $second => 'second', $third => 'third'))
 *  - an instance of Traversable f.e. Validator($config_instance)
 *
 * @param array|Traversable $options
 */
public function __construct($options = null)
{
    // ...
}

Everything works fine using the first approach above, and it may be a deliberate design decision for the Regex contructor parameter to be mandatory, but it appeared out of place to me so I thought it worth mentioning in case this was an oversight.


Originally posted by @mrobinsonuk at zendframework/zend-validator#200

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) {
}

Originally posted by @FabianKoestring at zendframework/zend-validator#68

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.


Originally posted by @jscssphtml at zendframework/zend-validator#13

preg_match(): Compilation failed: regular expression is too large at offset 156184

This happens while using Zend\Validator\Hostname->isValid('[email protected]') because hostname/Biz.php contains enormous regular expression

Trace looks like this:

preg_match('/^[\x{002d}0-9a-z\x{3447}\x{3473}\x{359..(156088 chars skipped)..9FA0}\x{9FA2}\x{9FA4}\x{9FA5}]{1,20}$/iu','tapi4457@hsoqvf')
/vendor/zendframework/zend-validator/src/Hostname.php:1877

PHP Version 7.1.7


Originally posted by @ac-dc at zendframework/zend-validator#219

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"


Originally posted by @igormx at zendframework/zend-validator#106

Package container-interop/container-interop is abandoned, you should avoid using it. Use psr/container instead.

Bug Report

Q A
Version(s) 2.13.0

Summary

When using "composer update" on my project, I started to get the warning:

Package container-interop/container-interop is abandoned, you should avoid using it. Use psr/container instead.

I investigated and found out that you include this package in this file

laminas/laminas-validator/composer.json

Current behavior

The "composer update" operation issues the warning.

How to reproduce

Create a dummy composer project and write in the composer.json

"require": {
...
"laminas/laminas-http": ">=2.11.2"
...
},

then do "composer update".

Expected behavior

No warning should be issued.

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.



Originally posted by @GeeH at zendframework/zend-validator#101

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

Originally posted by @bakura10 at zendframework/zend-validator#1

ZF3 Using Explode with InArray validator as child breaks validation messages format

I am using the following array notation in my form creation for a single select element:

'validators' => [
[
	'name' => 'Explode',
	'options' => [
		'validator' => [
			'name'=>'InArray', 
			'options'=>[
				'haystack'=>[1,2],
				'message'=> 'Invalid status'
			]
		]
	]
],
]

When I submit an invalid option, I get this from $form->getMessages():

  array (size=3)
  'status' => 
    array (size=2)
      'notInArray' => string 'The input was not found in the haystack' (length=39)
      0 => 
        array (size=1)
          'notInArray' => string 'Invalid status' (length=14)

Without the Explode layer in the validators,

[
     'name'=>'InArray', 
     'options'=>[
          'haystack'=>[1,2],
          'message'=>'Invalid status'
     ]
],

$form->getMessages() reports this when invalid:

array (size=3)
  'status' => 
    array (size=1)
      'notInArray' => string 'Invalid status' (length=14)

Since Explode does not acknowledge a message option and when I set disable_inarray_validator to true I still get:

  'status' => 
    array (size=2)
      'notInArray' => string 'The input was not found in the haystack' (length=39)
      0 => 
        array (size=1)
          'notInArray' => string 'Invalid status' (length=14)

What I am expecting to get is:

'status' => 
    array (size=1)
      'notInArray' => 
        array (size=1)
          0 => string 'Invalid status' (length=14)

From what I can tell, Explode is a utility to help process validators rather than being an actual validator. But in using it, it breaks validation messages so my standard code for processing form validation messages does not work.


Originally posted by @dabroderick at zendframework/zend-validator#230

[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.



Originally posted by @GeeH at zendframework/zend-validator#98

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


Originally posted by @h3christophe at zendframework/zend-validator#69

Proposal: Validation for breached passwords

Hi,

I'm maintainer of dragonbe/hibp, a composer package to validate passwords against the Have I been pwned? API service to see if a provided password was already used in a breach.

Today (April 5, 2019) Symfony announced they integrate the same service as a validation component in their 4.3 version and I see this as a good way to offer this functionality as part of the framework toolkit. Too bad they're not using my service though.

So I want to propose a validation rule to check provided passwords against HIBP API.


Originally posted by @DragonBe at zendframework/zend-validator#259

AbstractValidator does not use messageKey when translating messages

I would like to translate validation messages using messageKeys as message strings may change. But translateMessage in AbstractValidator does not use $messageKey parameter for translating, even if it is defined as method parameter. It uses message string to translate.

protected function translateMessage($messageKey, $message)
{
    $translator = $this->getTranslator();
    if (! $translator) {
        return $message;
    }
    return $translator->translate($message, $this->getTranslatorTextDomain());
}

Originally posted by @bkilinc at zendframework/zend-validator#260

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;
}



Originally posted by @GeeH at zendframework/zend-validator#97

Psalm integration

Feature Request

Q A
QA yes

Summary

As decided during the Technical-Steering-Committee Meeting on August 3rd, 2020, Laminas wants to implement vimeo/psalm in all packages.

Implementing psalm is quite easy.

Required

  • Create a .psalm.xml.dist in the project root
  • Copy and paste the contents from this psalm.xml.dist
  • Run $ composer require vimeo/psalm
  • Run $ vendor/bin/psalm --set-baseline=psalm-baseline.xml
  • Add a composer script static-analysis with the command psalm --shepherd --stats
  • Add a new line to script: in .travis.yml: - if [[ $TEST_COVERAGE == 'true' ]]; then composer static-analysis ; fi
  • Remove phpstan from the project (phpstan.neon.dist, .travis.yml entry, composer.json require-dev and scripts)
Optional
  • Fix as many psalm errors as possible.

PHP 8.0 support

Feature Request

Q A
New Feature yes

Summary

To be prepared for the december release of PHP 8.0, this repository has some additional TODOs to be tested against the new major version.

In order to make this repository compatible, one has to follow these steps:

  • Modify composer.json to provide support for PHP 8.0 by adding the constraint ~8.0.0
  • Modify composer.json to drop support for PHP less than 7.3
  • Modify composer.json to implement phpunit 9.3 which supports PHP 7.3+
  • Modify .travis.yml to ignore platform requirements when installing composer dependencies (simply add --ignore-platform-reqs to COMPOSER_ARGS env variable)
  • Modify .travis.yml to add PHP 8.0 to the matrix (NOTE: Do not allow failures as PHP 8.0 has a feature freeze since 2020-08-04!)
  • Modify source code in case there are incompatibilities with PHP 8.0

Duplicated factory definition for Laminas\I18n\Validator\IsInt in Laminas\Validator\ValidatorPluginManager

Bug Report

Q A
Version(s) 2.13.4

Summary

There is a duplicated factory definition for Laminas\I18n\Validator\IsInt in Laminas\Validator\ValidatorPluginManager on lines 368 and 373.

Current behavior

The factory definition is duplicated.

How to reproduce

Open src/ValidatorPluginManager.php and go to lines 368 and 373.

Expected behavior

There should be only one factory definition for the same class.

MimeType validator doesn't work for multiple files.

Hi,

The IsImage validator doesn't work with html5 file inputs that have the multiple attribute assigned.

It validates the first file file, then gives the error :

Warning: finfo_file(): 557 is not a valid file_info resource in vendor/zendframework/zend-validator/src/File/MimeType.php on line 387

Warning: finfo_close(): 557 is not a valid file_info resource in vendor/zendframework/zend-validator/src/File/MimeType.php on line 388

Ideally, the behaviour is that it won't pass validation unless all of the files are images?

Thanks


Originally posted by @gavinlimely at zendframework/zend-validator#170

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

Originally posted by @autowp at zendframework/zend-validator#114

[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.



Originally posted by @GeeH at zendframework/zend-validator#95

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]);

Originally posted by @tomp4l at zendframework/zend-validator#82

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);

Originally posted by @SBC-Fujian at zendframework/zend-validator#85

RecordExists and NoRecordExists is not reusable for validate different values

Custom modification in method for debug: https://github.com/zendframework/zend-validator/blob/master/src/Db/AbstractDb.php#L321

    protected function query($value)
    {
        $sql = new Sql($this->getAdapter());
        $select = $this->getSelect();
        $statement = $sql->prepareStatementForSqlObject($select);
        $parameters = $statement->getParameterContainer();
        $parameters['where1'] = $value; // <- PROBLEM
        echo $statement->getSql() . "\n"; // <- DEBUG
        $result = $statement->execute();
        return $result->current();
    }

test case:

        $validator = new RecordExists([
            'table'   => 'tags',
            'field'   => 'id',
            'adapter' => $this->getEvent()->getApplication()->getServiceManager()->get('DBSiteAdapter')
        ]);
        print_r($validator->isValid(1)); echo "\n";
        print_r($validator->isValid(2)); echo "\n";

result:

SELECT "tags"."id" AS "id" FROM "tags" WHERE "id" = :where1
1
SELECT "tags"."id" AS "id" FROM "tags" WHERE "id" = :where2
PDO EXCEPTION: SQLSTATE[HY093]: Invalid parameter number: :where1

as we see, in next call we have :where2 instead :where1


Originally posted by @AndrejAndb at zendframework/zend-validator#178

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


Originally posted by @038291 at zendframework/zend-validator#102

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.



Originally posted by @GeeH at zendframework/zend-validator#99

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.


Originally posted by @Saeven at zendframework/zend-validator#41

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.



Originally posted by @GeeH at zendframework/zend-validator#100

MimeType validator possibly leads to memory exhausted fatal error

Test case:

<?php

include 'vendor/autoload.php';

ini_set('memory_limit', '16M'); // might also happen with default 128M, lowering it here just to ensure test fail

$mimeValidator = new Zend\Validator\File\MimeType(['text/plain']);

file_put_contents('/tmp/foobar', 'test');

var_dump($mimeValidator->isValid('/tmp/foobar'));

unlink('/tmp/foobar');

The problem is finfo_open'ing magic file can be quite noisy (producing a whole lot of warnings) when it isn't super satisfied with a given magic file - albeit still working.
This and the fact the mime validator utilizes Zend\Stdlib\ErrorHandler to suppress notices/warnings - which, under the hood, keeps track of all the exceptions occurred (until the stop is invoked) - could lead to a memory exhausted fatal in memory-limited environment.

Tested on Ubuntu 16.04/17.04 php-7.1.1

I think one of the possible "fixes" (reliability improvement) might be to set an actual explicit ignore error handler (and not use the generic ErrorHandler::start ignoring it's results afterwards)
So, instead of doing:

                ErrorHandler::start(E_NOTICE | E_WARNING);
                $this->finfo = finfo_open(FILEINFO_MIME_TYPE, $mimefile);
                ErrorHandler::stop();

the errorHandler could be explicitly requested to ignore the errors of given levels: ErrorHandler::ignore(E_NOTICE | E_WARNING);

This would however require changing of Stdlib/ErroHandler as it doesn't provide the ignore functionality atm.

Not only this would prevent the aforementioned use-case failure, it would both have improvements on performance (saving some memory and cpu cycles) and express the intention more clearly in the code.


Originally posted by @sserbin at zendframework/zend-validator#207

Running URI through UriNormalize Filter appends `/` - causes Hostname TLD check to always fail

If you run any hostname through UriNormalize, at some point the normalize function in the Uri module is run. This module calls normalizePath function.

This function appends a / to the end of the URI.

Next, when you try to validate the URI with Hostname validator with 'useTldCheck' => true, in the options, it will always fail.

hostname


Steps to reproduce

Have the following in a fieldset

        $this->add(
            [
                'name'       => 'someUrl',
                'required'   => true,
                'type'       => Text::class,
                'options'    => [
                    'label' => 'Some URL',
                ],
                'attributes' => [
                    'maxlength' => 100,
                ],
            ]
        );

Have the following in an InputFilter:

        $this->add(
            [
                'name'       => 'someUrl',
                'required'   => true,
                'filters'    => [
                    ['name' => StringTrim::class],
                    ['name' => StripTags::class],
                    [
                        'name'    => ToNull::class,
                        'options' => [
                            'type' => ToNull::TYPE_STRING,
                        ],
                    ],
                    [
                        'name'    => UriNormalize::class,
                        'options' => [
                            'enforcedScheme' => 'https',
                        ],
                    ],
                ],
                'validators' => [
                    [
                        'name'    => StringLength::class,
                        'options' => [
                            'min' => 1,
                            'max' => 100,
                        ],
                    ],
                    [
                        'name'    => Hostname::class,
                        'options' => [
                            'allow'       => Hostname::ALLOW_DNS,
                            // Allow only DNS names
                            'useIdnCheck' => true,
                            // Check IDN domains - International Domain Names - supports international characters in DNS of country TLD, e.g. *.de (Germany) TLD
                            'useTldCheck' => true,
                            // Validates the existence of the TLD itself (the .com part of the domain)
                        ],
                    ],
                    [
                        'name'    => Uri::class,
                        'options' => [
                            'allowRelative' => false,
                        ],
                    ],
                ],
            ]
        );

I've got a few more issues reported that I'm solving, next to projects and a full-time job, I most likely will not have time to fix this. Would appreciate someone stepping in to fix this one. If not I might get around to it after other issues in zend-form and/or zend-inputfilter are finished.


Originally posted by @rkeet at zendframework/zend-validator#235

[WIP] Refactor to stateless validators

This work-in-progress is exploring how we might approach stateless validators.

Essentially, instead of an isValid() method returning a boolean, and a subsequent call on the validator to retrieve validation error messages, we would instead:

  • Define a Result interface modeling the results of validation; it would compose the value validated, validation status, and, if present, any validation error messages.
  • Define validators would define a single validate() method, accepting both a value and optional context, and return a Result instance.
  • Define a ResultAggregate interface for aggregating several results, as is necessary in a ValidatorChain; Result instances would be pushed upon an aggregate.

Translation, value obscuration, and message truncation then become presentation issues, and can be achieved by decorating Result instances.

Additionally, we'd remove the concept of $options for creating individual validator instances; they would instead have concrete constructor arguments. This simplifies a ton of logic internally, but means that each validator would require its own factory class. On the flip side, it also means developers can write factories for specific options combinations, and have shared instances without worrying about state.

Migration concerns

We could create a new minor release that adds the new Validator, Result, and ResultAggregate interfaces, and various Result implementations. Validator would define validate instead of isValid(), allowing devs to implement both in order to forward-proof their validators. We could also provide a wrapper for Validator implementations to make them work as ValidatorInterface instances; in such a case, it would pull info from the result in order to populate its members.

The bigger issue is existing validators, and extensions to them. Developers extending existing validators may want to copy/paste implementations and begin migration of those to make them forwards-compatible with version 3. Since we would have version 3 released simultaneously to a v2 with the new interface additions, they could even copy those from v3 to aid their migration.

Integration concerns

I have not yet investigated impact on zend-inputfilter; however, that version will require a similar refactor towards stateless inputs/input filters as well.


Originally posted by @weierophinney at zendframework/zend-validator#181

Interface to add valid TLDs in Hostname validator

I recently used this validator but found it did not support .car TLD. The company I work for recently purchased such a domain and we needed to allow valid email addresses with that TLD.

I needed to extend the existing validator and also extend the EmailAddress validator to be able to reach the TLD list and then could attach the new validator in Apigility and add a list of TLDs, which were pushed onto the array in Hostname validator.

It would have been quite useful to just have a public function in Hostname validator to add to the validTlds array. That is what I am proposing to do myself.


Originally posted by @peterkeatingie at zendframework/zend-validator#117

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.