siriusphp / validation Goto Github PK
View Code? Open in Web Editor NEWFramework agnostic validation library for PHP
Home Page: http://www.sirius.ro/php/sirius/validation/
License: MIT License
Framework agnostic validation library for PHP
Home Page: http://www.sirius.ro/php/sirius/validation/
License: MIT License
$ruleFactory->setMessages('email', $defaultMessageWithoutLabel, $defaultMessageWithLabel);
But RuleFactory
does not have setMessages()
function.
$this->success = strlen($value) <= $this->options['max'];
https://github.com/kenjis/siriusphp-validation/blob/master/src/Rule/MaxLength.php#L24
strlen() returns the number of bytes rather than the number of characters in a string.
http://php.net/manual/en/function.strlen.php
Why don't you use mb_strlen()
?
If i add rule
regex((\+7)?\d\d\d-\d\d\d\d\d\d\d)
then i got Regex rule with just (\+7
parsed.
As temporarily workaround i'd preferred to add some rules in list of addMultiple() as Regex instances. But it is also impossible for now :(
Hello, I'm creating a middleware that implements your validation. Unfortunately, I'm having issues with a mixed validation.
Hopefully, you can help me out.
My rules are:
$validator = new \Sirius\Validation\Validator();
$validator->add(
[
'latitude' => ['requiredWith(longitude)', 'number'],
'longitude' => ['requiredWith(latitude)', 'number']
]
);
$result = $validator->validate([]);
var_dump($result); // Returns false
In theory, the number
rule should be checked for both latitude and longitude, if any of the two is passed, but it reality it does not and validate returns false.
Am I setting the rules incorrectly or is this the expected behaviour?
I'm running version 2.2, PHP 7.1
Both rules fail, a temporary solution would be to Regex ^\d{10}$
Hi I am using the latest version of this and trying to validate an uploaded file and date like so:
$validator->add(
[
'learner-name:Name' => 'required',
'learner-license:License number' => 'required',
'learner-email:Email' => 'required | email',
'learner-mobile:Mobile' => 'required | minlength(11)',
'learner-ted:Theory expiry date' => 'date',
'learner-dlp:License Photo' => 'upload\required | upload\image',
'course-id:Course not chosen' => 'integer'
]
);
The date field throws an error:
Warning: date() expects at most 2 parameters, 3 given
any format I send gives that warning.
And the file upload never gets evaluated, am I missing something?
I stumble across this error when using the RequiredWithout
validation rule, but after looking into it, it appears to also be present in the RequiredWhen
and RequiredWith
rules.
Those rules will try to trim
the value of the parameter to validate it, but the value can be an integer, where the trim
function will throw an exception.
Because we have conditional required rules we need to set item values to NULL for those rules as well. This is prone to error, so we need to work with whatever data we receive and not set NULL values when some items are missing
Match is a reserved word in PHP8
When use build-in ruls Url
in PHP 7.3 , it will throw Exception:
filter_var(): explicit use of FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED is deprecated
From PHPMailer/PHPMailer#1551 , I hope this patch can help you fix this bug:
Index: vendor/siriusphp/validation/src/Rule/Url.php
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
--- vendor/siriusphp/validation/src/Rule/Url.php (date 1560607388394)
+++ vendor/siriusphp/validation/src/Rule/Url.php (date 1560607388394)
@@ -9,7 +9,7 @@
public function validate($value, $valueIdentifier = null)
{
$this->value = $value;
- $this->success = (bool) filter_var($value, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);
+ $this->success = (bool) filter_var($value, FILTER_VALIDATE_URL);
return $this->success;
}
Use constants for the rules
$validator->add('email_address', Validator::RULE_EMAIL);
Validation of "testümläü[email protected]" fails when i use default $patternselect value "php". This could be fixed by changing
return (bool) filter_var($address, FILTER_VALIDATE_EMAIL);
to
return (bool) filter_var($address, FILTER_VALIDATE_EMAIL, FILTER_FLAG_EMAIL_UNICODE);
And another rules that may contain value 0 as param are not working (likely).
This is related for rules that declared as a string.
Cause, see
ValueValidator::parseRule()
- https://github.com/siriusphp/validation/blob/2.2.0/src/ValueValidator.php#L220
and
AbstractRule::normalizeOptions()
- https://github.com/siriusphp/validation/blob/2.2.0/src/Rule/AbstractRule.php#L93
Row
if (isset($matches[1][0]) && $matches[1][0]) {
may be replace to
if (isset($matches[1][0]) && $matches[1][0] !== '') {
but
if (! $options) {
I don't know how to fix it correctly.
Move the functionality to create validators into a factory
Hello there, thanks for the brilliant library. I wanted to know if there is a built in way to post back passed values to the form if some fail validation e.g. in a form of 3 inputs 2 passed and 1 failed, when the user returns to the form after validation the passed fields are already filled in. Hope that makes sense. Cheers
It would be awesome if Validator would also filter out unknown elements and provide filtered input.
An example should sched some light:
$data = [
'id' => '123',
'email' => '[email protected]',
'text' => 'some text here',
'submit' => 'Send',
'some_value_user_posted' => '123',
// other unknown/unused fields
];
$validator = new \Sirius\Validation\Validator();
$validator->add([
'id' => 'required|number',
'email' => 'required|email',
'text' => 'required'
]);
if(!$validator->validate($data)){
send_errors($validator->getMessages());
}else{
$clean_data = $validator->data();
// and $clean_data contains only id, email and text, nothing else
}
Hi, I would like to participate in your project, do you have a contribution guide? to-do list? or some info I could use to help?
I think you maintain compatibility with PHP 5.3 because of WP. Is my assumption right?
Have you consider open a communication line like gitter?
These are some ideas:
When a value selector has different validation rules and you want to customize the error message with the label you have to provide the label multiple times
$validator->add(array(
'preference[*][notification][after][timeout]' => array(
array('required', null, '{label} is required', 'After Timeout'),
array('Number', null, '{label} must be a valid number', 'After Timeout'))
));
Implement a way to reduce this code.
Hi,
Either I'm missing something completely obvious or might there be bug in the version 2.1.
It seems that, when passing an array to the add
method, it only adds or evaluates the first rule.
$validator = new Validator();
$input = ['title' => 'Some title'];
$validator->add(array(
'title:Title' => 'required',
'content:Content' => 'required | minlength(5)',
));
if ($validator->validate($input)) {
echo "all good";
} else {
var_dump($validator->getMessages();
}
If you run this code, it returns true
even though the content
is not included in the $input
array. But the funny thing is, even if I change the $input
to:
$input = ['title' => 'Some title', 'content' => 'foo'];
This still returns true, even though content is less than 5 chars.
What am I missing?
thanks,
Unless I am missing something, most rules should not be validated (or validation should return true) if the input is null or an empty string (except for Required, Length and some others).
Here is an example where Email, AlphaNumeric, AlphaNumHyphen and Alpha is failing validation, but is not required:
<?php
require 'vendor/autoload.php';
$input = [
'name' => 'Christiaan',
'email' => '',
'address' => [
'line_1' => '',
'line_2' => '',
'country' => ''
]
];
$validator = new Sirius\Validation\Validator;
$validator
->add('name', ['Required', 'AlphaNumeric'])
->add('email', ['Email'])
->add('address[line_1]', ['AlphaNumeric'])
->add('address[line_2]', ['AlphaNumHyphen'])
->add('address[country]', ['Alpha'])
->validate($input);
?>
<pre><?php print_r($validator->getMessages()); ?></pre>
Returns:
Array
(
[email] => Array
(
[0] => Sirius\Validation\ErrorMessage Object
(
[template:protected] => This input must be a valid email address
[variables:protected] => Array
(
[value] =>
)
)
)
[address[line_1]] => Array
(
[0] => Sirius\Validation\ErrorMessage Object
(
[template:protected] => This input can contain only letters and digits
[variables:protected] => Array
(
[value] =>
)
)
)
[address[line_2]] => Array
(
[0] => Sirius\Validation\ErrorMessage Object
(
[template:protected] => This input can contain only letters, digits, spaces, hyphens and underscores
[variables:protected] => Array
(
[value] =>
)
)
)
[address[country]] => Array
(
[0] => Sirius\Validation\ErrorMessage Object
(
[template:protected] => This input can contain only letters
[variables:protected] => Array
(
[value] =>
)
)
)
)
Greets
I'm trying out Sirius/Validation for the first time but experiencing an issue or two.
Version: 2.2
In my case, the length(10,32) and regex() are not validating as expected:
<?php
require_once("vendor/autoload.php");
use Sirius\Validation\Validator;
$data =<<<EOD
{
"method": "create",
"backend": {
"client": "my&"
}
}
EOD;
$data = json_decode($data,true);
$validator = new Validator();
$validator->add('method', 'required');
$validator->add('method', 'inlist', array('list'=>array('create',)));
$validator->add('backend', 'arraylength', array('min'=>1,'max'=>1));
$validator->add('backend[*]client', 'required');
$validator->add('backend[*]client', 'length', array('min'=>10,'max'=>32)); // FAILS TO VALIDATE
$validator->add('backend[*]client', 'regex', '/^[a-z0-9-]+$/'); // FAILS TO VALIDATE
if ($validator->validate($data)) {
print "OK\n";
} else {
// send the error messages to the view
print_r($validator->getMessages());
}
I'd appreciate any pointers.
Thanks
Henry
Scenario: I'm developing an API-centric application so every form submission are done in AJAX. The response headers are application/json
so I need to json_encode
the data. But that causes the messages in the validator to output nothing.
I have a dirty workaround for this.
/**
* Format messages and make them string for json output.
*
* @param array $messages
* @return array
*/
protected function formatMessagesForJsonOutput(array $messages)
{
$formatter = function ($value)
{
return (string) $value[0];
};
return array_map($formatter, $messages);
}
It would be great if the library automatically convert the error messages into string for json_encode
.
Q | A |
---|---|
BC Break | yes |
Version | 3.0.2 and dev-master |
nothing fancy, i'm just trying to validate an array and the error (warn) happen.
and this is the log.
Deprecated: Return type of Sirius\Validation\RuleCollection::attach($rule, $data = null) should either be compatible with SplObjectStorage::attach(object $object, mixed $info = null): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /home/boku/Public/php-sandbox/adr-skeleton/vendor/siriusphp/validation/src/RuleCollection.php on line 8
Deprecated: Return type of Sirius\Validation\RuleCollection::getHash($rule) should either be compatible with SplObjectStorage::getHash(object $object): string, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /home/boku/Public/php-sandbox/adr-skeleton/vendor/siriusphp/validation/src/RuleCollection.php on line 30
i have this code in slim 4 controller and serve it with php (PHP 8.1.7)
dev server.
$input = [
'email'=>'email@me',
];
$this->valid->add('email', ['required', 'email']);
$data = $this->valid->validate($input);
var_dump($data);
var_dump($input);
this function only returns erros on the first element when trying to validate a data array(), and the custom error message is not parsed nore taken into account
for something like
array('name', 'required | maxlength(max=25) | minlength(min=3)({label} must have between {min} and {max} characters)(Name)',
'activity', 'required | maxlength(max=25) | minlength(min=3)({label} must have between {min} and {max} characters)(Activity)');
I get
array(1) { ["name"]=> array(1) { [0]=> object(Sirius\Validation\ErrorMessage)#713 (2) { ["template":protected]=> string(22) "This field is required" ["variables":protected]=> array(1) { ["value"]=> string(0) "" } } } }
Would it be possible to use filtration inside the same rule syntax?
$validator->add('title', 'required | maxlength(max=255) | minlength(min=10) | sirius(strip_tags)');
Thanks for putting work into this, useful class which I'll be using.
in code of rule Length, in function validate, use incorrect class for max and min validator
$maxValidator = new MinLength();
$minValidator = new MaxLength();
need use MaxLength for $maxValidator, and MinLength for $minValidator
Could you post here or update docs on how to properly use the regex syntax within sirius.
How would you pass a pattern using match?
It has uses on the Sirius\Upload and Sirius\Forms which depends on Sirius\Validation so why not make it reusable.
If I send empty value from form (as empty string), this value will be tested (eg, Integer, GreaterThan), even if it is not required.
See https://github.com/siriusphp/validation/blob/2.2.1/src/ValueValidator.php#L258
In line 32 of RuleFactory, there is a typo in Validator::RULE_ARRAY_MIN_LENGTH => 'ArrayMinLengh',
. It should be ArrayMinLength
.
Hello,
When i used "AlphaNumHyphen" validator for an array object, php has gave a notice and it's validation returned true.
$object = ['array' => ['field1', 'field2']];
$validation->add('array', 'required');
$validation->add('array', 'AlphaNumHyphen');
$validation->validate($object);
"A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: Rule/AlphaNumHyphen.php
Line Number: 23"
and return true.
PHP Version: 5.6
Sirius/validation: 2.1.2
Hope to add two new Build-in Validator NotMatch
and NotEqual
, which behavior like NotRegex
to Regex
.
Error: Call to undefined method Sirius\Validation\Validator::getMessage()
the function is not defined in Sirius\Validation\Validator
Is there a way to check against a list of values inside an array. E.g.
$acceptedValues = array("value1","value2");
Only validate if user input is equal to what's inside an array
filter_var($value, FILTER_VALIDATE_EMAIL) !== false
instead of using regex
Hi when I try to retrieve errors with $validator->getMessages()
I get a unformatted response. I've reverted back to an older version where this does not happen.
I'm referring to this part: {label} is required
[0] => Sirius\Validation\ErrorMessage Object
(
[template] => {label} is required
[variables] => Array
(
[label] => Name
[value] =>
)
)
case:
$validator->add(array(
'name:Name' => 'required | maxlength(100)',
'username:Username' => 'required | maxlength(100)',
));
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.