I need to know how to apply the "matches" validation rule in Kohana 3.1. I've tried the following rule in my model with no success:
'password_confirm' => array(
array('matches', array(':validation', ':field', 'password')),
)
But it always fails. I put a var_dump($array) in the first line of the Valid::matches() method. I paste it below:
/**
* Checks if a field matches the value of another field.
*
* #param array array of values
* #param string field name
* #param string field name to match
* #return boolean
*/
public static function matches($array, $field, $match)
{
var_dump($array);exit;
return ($array[$field] === $array[$match]);
}
It prints an object of type Validation and if I do var_dump($array[$field]) it prints null.
Thanks a lot in advance.
UPDATE: Also I figured out by the validation message that the order of the parameters of the rule should be inverted to this:
'password_confirm' => array(
array('matches', array(':validation', 'password', ':field')),
)
Your syntax is correct, but I'm going to guess and say that your DB schema does not have a 'password_confirm' column so you are trying to add a rule to a field that doesn't exist.
Regardless, the right place to perform password confirm matching validation is not in your model but as extra validation that is passed to your model in your controller when you attempt to save.
Put this in your user controller:
$user = ORM::Factory('user');
// Don't forget security, make sure you sanitize the $_POST data as needed
$user->values($_POST);
// Validate any other settings submitted
$extra_validation = Validation::factory(
array('password' => Arr::get($_POST, 'password'),
'password_confirm' => Arr::get($_POST, 'password_confirm'))
);
$extra_validation->rule('password_confirm', 'matches', array(':validation', 'password_confirm', 'password'));
try
{
$user->save($extra_validation);
// success
}
catch (ORM_Validation_Exception $e)
{
$errors = $e->errors('my_error_msgs');
// failure
}
Also, see the Kohana 3.1 ORM Validation documentation for more information
Related
I have a request that takes several input. I want the 'salary' input to be validated only if the salary_type is equal to "exact". Else, I don't want to have any message about it.
However, now, even if salary_type is equal to "range", I still get an error that "salary must be an integer".
How can I make sure there isn't any error unless the field is required?
Thanks!
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreJobOfferRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required|string|min:3',
'description' => 'required|string|min:10',
'city' => 'required|string|min:3',
'salary_type' => 'required|in:range,exact',
'min_salary' => 'required_if:salary_type,range|integer|min:0',
'max_salary' => 'required_if:salary_type,range|integer|min:0',
'salary' => 'required_if:salary_type,exact|integer|min:0',
'fieldsOfWork' => 'required|exists:field_of_works,id',
'job_type.*' => 'required|exists:job_types,id',
"trainings.*" => 'required|exists:trainings,id',
"availability.*" => 'required|exists:trainings,id'
];
}
}
required and required_if do not stop the rest of the validation rules from being executed. It just expects the value not to be null, an empty string, and empty Countable object or an uploaded file with no path. If the field is set, the required rule will just be skipped and the next rule is applied.
So, the required_if rule for salary will skip if salary_type is not 'exact', and continue validating if it's an integer and min 0. This behavior is confusing to a lot of new Laravel developers.
There is an exclude_if rule that does what you probably expect:
'salary' => 'exclude_if:salary_type,exact|integer|min:0',
This will exclude the whole field under validation from the request data that will be returned by validate() and $request->validated() methods if the condition is not met. So if salary_type is not 'exact', the salary field will be gone but the validation will pass.
If salary_type is 'exact', however, it will be validated for being a min 0 integer value.
Please note that the exclude_if rule was added in Laravel 6, so this doesn't work for previous versions of Laravel. See https://laravel.com/docs/8.x/validation#conditionally-adding-rules for details on conditional validation.
We are building an api endpoint where precision is required. We want to enforce strict validation on the parameters that are POST/PUT to the server.
If the api user sends a key=value pair that is not supported (eg. we allow the parameters [first_name, last_name] and the user includes an unsupported parameter [country]), we want the validation to fail.
Have tried building a custom validator called allowed_attributes (used as allowed_attributes:attr1,attr2,...), but for it to be usable in a $validationRules array, it has to be applied to the parent of a list of nested/child attributes (...because otherwise our custom validator did not have access to the attributes being validated).
Validator::extend('allowed_attributes', 'App\Validators\AllowedAttributesValidator#validate');
This created issues with other validators, where we then had to anticipate this parent/child structure and code around it, including additional post-validation clean-up of error keys and error message strings.
tl;dr: very dirty, not a clean implementation.
$validationRules = [
'parent' => 'allowed_attributes:first_name,last_name',
'parent.first_name' => 'required|string|max:40',
'parent.last_name' => 'required|string|max:40'
];
$isValid = Validator::make(['parent' => $request], $validationRules);
var_dump("Validation results: " . ($isValid ? "passed" : "failed"));
Any ideas/suggestions on how this can be accomplished more cleanly in laravel, without requiring the use of parent/child relationship to get access to the list of all $request attributes (within the custom validator)?
I preferred to post a new answer as the approach is different from the previous one and a bit more cleaner. So I would rather keep the two approaches separated and not mixed together in the same answer.
Better problem handling
After digging deeper into the Validation's namespace's source code since my last answer I figured out that the easiest way would have been to extend the Validator class to remplement the passes() function to also check what you needed.
This implementation has the benefit to also correcly handle specific error messages for single array/object fields without any effor and should be fully compatible with the usual error messages translations.
Create a custom validator class
You should first create a Validator class within your app folder (I placed it under app/Validation/Validator.php) and implement the passes method like this:
<?php
namespace App\Validation;
use Illuminate\Support\Arr;
use Illuminate\Validation\Validator as BaseValidator;
class Validator extends BaseValidator
{
/**
* Determine if the data passes the validation rules.
*
* #return bool
*/
public function passes()
{
// Perform the usual rules validation, but at this step ignore the
// return value as we still have to validate the allowance of the fields
// The error messages count will be recalculated later and returned.
parent::passes();
// Compute the difference between the request data as a dot notation
// array and the attributes which have a rule in the current validator instance
$extraAttributes = array_diff_key(
Arr::dot($this->data),
$this->rules
);
// We'll spin through each key that hasn't been stripped in the
// previous filtering. Most likely the fields will be top level
// forbidden values or array/object values, as they get mapped with
// indexes other than asterisks (the key will differ from the rule
// and won't match at earlier stage).
// We have to do a deeper check if a rule with that array/object
// structure has been specified.
foreach ($extraAttributes as $attribute => $value) {
if (empty($this->getExplicitKeys($attribute))) {
$this->addFailure($attribute, 'forbidden_attribute', ['value' => $value]);
}
}
return $this->messages->isEmpty();
}
}
This would essentially extend the default Validator class to add additional checks on the passes method. The check compute the array difference by keys between the input attributes converted to dot notation (to support array/object validation) and the attributes which have at least one rule assigned.
Replace the default Validator in the container
Then the last step you miss is to bind the new Validator class in the boot method of a service provider. To do so you can just override the resolver of the Illuminate\Validation\Factory class binded into the IoC container as 'validator':
// Do not forget the class import at the top of the file!
use App\Validation\Validator;
// ...
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
$this->app->make('validator')
->resolver(function ($translator, $data, $rules, $messages, $attributes) {
return new Validator($translator, $data, $rules, $messages, $attributes);
});
}
// ...
Pratical use in a controller
You don't have to do anything specific to use this feature. Just call the validate method as usual:
$this->validate(request(), [
'first_name' => 'required|string|max:40',
'last_name' => 'required|string|max:40'
]);
Customize Error messages
To customize the error message you just have to add a translation key in your lang file with a key equal to forbidden_attribute (you can customize the error key name in the custom Validator class on the addFailure method call).
Example: resources/lang/en/validation.php
<?php
return [
// ...
'forbidden_attribute' => 'The :attribute key is not allowed in the request body.',
// ...
];
Note: this implementation has been tested in Laravel 5.3 only.
It should work for simple key/value pairs with this custom validator:
Validator::extendImplicit('allowed_attributes', function ($attribute, $value, $parameters, $validator) {
// If the attribute to validate request top level
if (strpos($attribute, '.') === false) {
return in_array($attribute, $parameters);
}
// If the attribute under validation is an array
if (is_array($value)) {
return empty(array_diff_key($value, array_flip($parameters)));
}
// If the attribute under validation is an object
foreach ($parameters as $parameter) {
if (substr_compare($attribute, $parameter, -strlen($parameter)) === 0) {
return true;
}
}
return false;
});
The validator logic is pretty simple:
If $attribute doesn't contains a ., we're dealing with a top level parameter, and we just have to check if it is present in the allowed_attributes list that we pass to the rule.
If $attribute's value is an array, we diff the input keys with the allowed_attributes list, and check if any attribute key has left. If so, our request had an extra key we didn't expect, so we return false.
Otherwise $attribute's value is an object we have to check if each parameter we're expecting (again, the allowed_attributes list) is the last segment of the current attribute (as laravel gives us the full dot notated attribute in $attribute).
The key here is to apply it to validation rules should like this (note the first validation rule):
$validationRules = [
'parent.*' => 'allowed_attributes:first_name,last_name',
'parent.first_name' => 'required|string|max:40',
'parent.last_name' => 'required|string|max:40'
];
The parent.* rule will apply the custom validator to each key of the 'parent' object.
To answer your question
Just don't wrap your request in an object, but use the same concept as above and apply the allowed_attributes rule with a *:
$validationRules = [
'*' => 'allowed_attributes:first_name,last_name',
'first_name' => 'required|string|max:40',
'last_name' => 'required|string|max:40'
];
This will apply the rule to all the present top level input request fields.
NOTE: Keep in mind that laravel validation is influenced by order of the rules as they are putted in rules array.
For example, moving the parent.* rule on bottom will trigger that rule on parent.first_name and parent.last_name; as opposed, keeping it as the first rule will not trigger the validation for the first_name and last_name.
This means that you could eventually remove the attributes that has further validation logic from the allowed_attributes rule's parameter list.
For example, if you would like to require only the first_name and last_name and prohibit any other field in the parent object, you might use these rules:
$validationRules = [
// This will be triggered for all the request fields except first_name and last_name
'parent.*' => 'allowed_attributes',
'parent.first_name' => 'required|string|max:40',
'parent.last_name' => 'required|string|max:40'
];
But, the following WON'T work as expected:
$validationRules = [
'parent.first_name' => 'required|string|max:40',
'parent.last_name' => 'required|string|max:40',
// This, instead would be triggered on all fields, also on first_name and last_name
// If you put this rule as last, you MUST specify the allowed fields.
'parent.*' => 'allowed_attributes',
];
Array Minor Issues
As far as I know, per Laravel's validation logic, if you were up to validate an array of objects, this custom validator would work, but the error message you would get would be generic on the array item, not on the key of that array item that wasn't allowed.
For example, you allow a products field in your request, each with an id:
$validationRules = [
'products.*' => 'allowed_attributes:id',
];
If you validate a request like this:
{
"products": [{
"id": 3
}, {
"id": 17,
"price": 3.49
}]
}
You will get an error on product 2, but you won't be able to tell which field is causing the problem!
I am working in Laravel 5.4 and I have a slightly specific validation rules need but I think this should be easily doable without having to extend the class. Just not sure how to make this work..
What I would like to do is to make the 'music_instrument' form field mandatory if program array contains 'Music'.
I found this thread How to set require if value is chosen in another multiple choice field in validation of laravel? but it is not a solution (because it never got resolved in the first place) and the reason it doesn't work is because the submitted array indexes aren't constant (not selected check boxes aren't considered in indexing the submission result...)
My case looks like this:
<form action="" method="post">
<fieldset>
<input name="program[]" value="Anthropology" type="checkbox">Anthropology
<input name="program[]" value="Biology" type="checkbox">Biology
<input name="program[]" value="Chemistry" type="checkbox">Chemistry
<input name="program[]" value="Music" type="checkbox">Music
<input name="program[]" value="Philosophy" type="checkbox">Philosophy
<input name="program[]" value="Zombies" type="checkbox">Zombies
<input name="music_instrument" type="text" value"">
<button type="submit">Submit</button>
</fieldset>
</form>
If I select some of the options from the list of check boxes I can potentially have this result in my $request values
[program] => Array
(
[0] => Anthropology
[1] => Biology
[2] => Music
[3] => Philosophy
)
[music_instrument] => 'Guitar'
Looking at validation rules here: https://laravel.com/docs/5.4/validation#available-validation-rules I think something like his should work but i am literally getting nothing:
$validator = Validator::make($request->all(),[
'program' => 'required',
'music_instrument' => 'required_if:program,in:Music'
]);
I was hoping this would work too but no luck:
'music_instrument' => 'required_if:program,in_array:Music',
Thoughts? Suggestions?
Thank you!
Haven't tried that, but in general array fields you usually write like this: program.*, so maybe something like this will work:
$validator = Validator::make($request->all(),[
'program' => 'required',
'music_instrument' => 'required_if:program.*,in:Music'
]);
If it won't work, obviously you can do it also in the other way for example like this:
$rules = ['program' => 'required'];
if (in_array('Music', $request->input('program', []))) {
$rules['music_instrument'] = 'required';
}
$validator = Validator::make($request->all(), $rules);
I know this post is older but if someone came across this issue again.
$validator = Validator::make($request->all(),[
'program' => 'required',
'music_instrument' => 'required_if:program,Music,other values'
]);
You could create a new custom rule called required_if_array_contains like this...
In app/Providers/CustomValidatorProvider.php add a new private function:
/**
* A version of required_if that works for groups of checkboxes and multi-selects
*/
private function required_if_array_contains(): void
{
$this->app['validator']->extend('required_if_array_contains',
function ($attribute, $value, $parameters, Validator $validator){
// The first item in the array of parameters is the field that we take the value from
$valueField = array_shift($parameters);
$valueFieldValues = Input::get($valueField);
if (is_null($valueFieldValues)) {
return true;
}
foreach ($parameters as $parameter) {
if (in_array($parameter, $valueFieldValues) && strlen(trim($value)) == 0) {
// As soon as we find one of the parameters has been selected, we reject if field is empty
$validator->addReplacer('required_if_array_contains', function($message) use ($parameter) {
return str_replace(':value', $parameter, $message);
});
return false;
}
}
// If we've managed to get this far, none of the parameters were selected so it must be valid
return true;
});
}
And don't forget to check there is a use statement at the top of CustomValidatorProvider.php for our use of Validator as an argument in our new method:
...
use Illuminate\Validation\Validator;
Then in the boot() method of CustomValidatorProvider.php call your new private method:
public function boot()
{
...
$this->required_if_array_contains();
}
Then teach Laravel to write the validation message in a human-friendly way by adding a new item to the array in resources/lang/en/validation.php:
return [
...
'required_if_array_contains' => ':attribute must be provided when ":value" is selected.',
]
Now you can write validation rules like this:
public function rules()
{
return [
"animals": "required",
"animals-other": "required_if_array_contains:animals,other-mamal,other-reptile",
];
}
In the above example, animals is a group of checkboxes and animals-other is a text input that is only required if the other-mamal or other-reptile value has been checked.
This would also work for a select input with multiple selection enabled or any input that results in an array of values in one of the inputs in the request.
The approach I took for a similar problem was to make a private function inside my Controller class and use a ternary expression to add the required field if it came back true.
I have roughly 20 fields that have a checkbox to enable the input fields in this case, so it may be overkill in comparison, but as your needs grow, it could prove helpful.
/**
* Check if the parameterized value is in the submitted list of programs
*
* #param Request $request
* #param string $value
*/
private function _checkProgram(Request $request, string $value)
{
if ($request->has('program')) {
return in_array($value, $request->input('program'));
}
return false;
}
Using this function, you can apply the same logic if you have other fields for your other programs as well.
Then in the store function:
public function store(Request $request)
{
$this->validate(request(), [
// ... your other validation here
'music_instrument' => ''.($this->_checkProgram($request, 'music') ? 'required' : '').'',
// or if you have some other validation like max value, just remember to add the |-delimiter:
'music_instrument' => 'max:64'.($this->_checkProgram($request, 'music') ? '|required' : '').'',
]);
// rest of your store function
}
Here my piece of code to solve that kind of trouble usind Laravel 6 Validation Rules
I tried to use the code above
public function rules()
{
return [
"some_array_field.*" => ["required", "integer", "in:1,2,4,5"],
"another_field" => ["nullable", "required_if:operacao.*,in:1"],
];
}
I need that when some_array_field has 1 in your value, another_field must be validated, otherwhise, can be null.
With the code above, doesn't work, even with required_if:operacao.*,1
If I change the rule for another_field to required_if:operacao.0,1 WORKS but only if the value to find is in index 0, when the order changes, validation fails.
So, I decided to use a custom closure function
Here's the final code for the example that works fine form me.
public function rules()
{
return [
"some_array_field.*" => ["required", "integer", "in:1,2,4,5"],
"another_field" => [
"nullable",
Rule::requiredIf (
function () {
return in_array(1, (array)$this->request->get("some_array_field"));
}
),
]
];
}
I hope that solve your trouble too!
I need help understanding the logic to deal with validating user inputs.
my current state of validating user data is at worst, i feel pretty awkward using these messy lines of codes, have a look at my typical function which i uses it to get input from the user and process it to database.
public function saveUser($arguments = array()) {
//Check if $arguments have all the required values
if($this->isRequired(array('name','email','password','pPhone','gender','roleId'))) {
//$name should could minimum of 5 and maximum of 25 chars, and is a strict character.
$name = $this->isString(5, 25, $this->data['name'], 'STRICT_CHAR');
$email = $this->isEmail($this->data['email']);
$pPhone = $this->isString(5, 12, $this->data['pPhone'], 'STRICT_NUMBER');
$sPhone = (!empty($this->data['sPhone'])) ? $this->isString(5, 12, $this->data['sPhone'], 'STRICT_NUMBER') : 0;
//Check For Duplicate Email Value
$this->duplicate('user_details','email',$email);
//If Static Variable $error is not empty return false
if(!empty(Validation::$error)) { return false; }
//After Validation Insert the value into the database.
$sth = $this->dbh->prepare('INSERT QUERY');
$sth->execute();
}
}
Now is the time i focus on improving my validation code. i would like all my class methods to validate the user inputs before inserting into the database. basically a class methods which takes user input should be able to perform the following.
If class method accepts user input as an array then check for all required inputs from within the array.
Check the Minimum and Maximum Length of the input.
Check for any illegal character.
etc.
I would like to know how to deal with this, and also if there is any PHP Independent Validation Component which can come to my rescue. it would be of great help. if i am doing it wrong please suggest me on improving my code, i won't mind going to any extent as long as it guarantees that my code follows the coding standard.
I will also appreciate if someone could explain me on dealing with validation logic for validating user input for a class method of an object.
Thank you..
PHP 5.2 has a new core extension called "filter functions". You can use this extension to sanitize and validate user data.
For example, to validate an email address:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "This (email) email address is considered valid.";
}
As for dealing with validation in general, you want to decouple the validation process from the incoming data and the objects themselves. I use the Lithium PHP framework, and their data validation class is implemented as a nearly independant utility class. Check it out for ideas on how to roll your own: http://li3.me/docs/lithium/util/Validator
Using their class, you get something like this:
// Input data. This can be an $object->data() or $_POST or whatever
$data = array(
'email' => 'someinvalidemailaddress';
);
// Validation rules
$rules = array(
'email' => array(
array('notEmpty', 'message' => 'email is empty'),
array('email', 'message' => 'email is not valid')
)
);
// Perform validation
Validator::check($data, $rules);
// If this were in your object
public validate($data = array(), $rules = array()) {
$data = !empty($data) ? $data : $this->data; // Use whatever data is available
$rules = $this->rules + $rules; // Merge $this's own rules with any passed rules
return Validator::check($data, $rules));
}
// You can have a save method like
public save() {
if ($this->validates()) {
// insert or update
}
}
// And your object would
$user = new User();
$user->data = array('email' => 'whatever');
$user->save();
And there's always Zend Validate. You can look it up at http://framework.zend.com/manual/en/zend.validate.set.html
Create your validation class first...Then when they submit the code. Just include the class on where every you have action set to on the form. You can create a loop to pass the POST or GET data though the instance which validates the input. Then if the input is good, return it(maybe as an array, that's what I do) and pass it to your database.
Example:
$validate = new validation_Class; //new instance of the validation class
$output = foreach($_POST as $input) // loop each input data into the class
{
$validate->$input;
}
Now if your validation class is setup right, you can have all the clean data stored in $output
I have an element. I want to add a custom validator and custom filter to it. The validator makes sure the input is one of several permitted values, then the filter adds some custom values to the input. This means I have to validate the original input first before running the filter. I do it in this order
$element = new Zend_Form_Element_Text('element');
$element->addValidator('PermittedValue', false);
$element->addFilter('TotalHyphen', false);
$this->addElement($element);
but this order isn't being respected. The filter runs first and changes the data, then the validator runs on the filtered data which means it always fails even for valid input. It seems from documentation that this is intentional
Note: Validation Operates On Filtered
Values Zend_Form_Element::isValid()
filters values through the provided
filter chain prior to validation. See
the Filters section for more
information.
How can I specify the order in which validators and filters run?
Sure seems like creating a custom element that supports post-validation filtering would be the way to go. How about this:
/**
* An element that supports post-validation filtering
*/
class My_Form_Element_PostValidateFilterable extends Zend_Form_Element_Text
{
protected $_postValidateFilters = array();
public function setPostValidateFilters(array $filters)
{
$this->_postValidateFilters = $filters;
return $this;
}
public function getPostValidateFilters()
{
return $this->_postValidateFilters;
}
public function isValid($value, $context = null)
{
$isValid = parent::isValid($value, $context);
if ($isValid){
foreach ($this->getPostValidateFilters() as $filter){
$value = $filter->filter($value);
}
$this->setValue($value);
}
return $isValid;
}
}
Usage would be something like this:
$elt = $form->addElement('PostValidateFilterable', 'myElement', array(
'label' => 'MyLabel',
'filters' => array(
'StringTrim',
// etc
),
'validators' => array(
'NotEmpty',
// etc
),
// here comes the good stuff
'postValidateFilters' => array(
new My_Filter_RunAfterValidateOne(),
new My_Filter_RunAfterValidateTwo(),
),
));
This keeps the validation and filtering in the form - keeping the controller thin.
Not tested, just a stab in the dark. And surely you could fatten/modify the API to add/remove filters by key, etc.
Whaddya think?
Maybe don't add the filter at all. Validate the content first in the controller, and then use the filter separately:
$request = $this->getRequest();
if ($request->isPost() && $form->isValid($request->getParams())) {
$filter = new Filter_Whatever();
$val = $filter->filter($request->getParam('element'));
... //call your model or whatever
}
I've never done this, but I suppose this (or something similar) might work.
Good point ! ,
AFAIK filters should or must run before validating the input :
from ZF docs
It's often useful and/or necessary to
perform some normalization on input
prior to validation. For example, you
may want to strip out all HTML, but
run your validations on what remains
to ensure the submission is valid. Or
you may want to trim empty space
surrounding input so that a
StringLength validator will use the
correct length of the input without
counting leading or trailing
whitespace characters.
but if and only if you are in case which can't solve mingos's answer must be the help
What you want to achieve is to change default behavior of how text element is being processed. Thus, I think you could create your own element (e.g. My_Form_Element_Text) that extends Zend_Form_Element_Text and overload its isValid() method.
Specifically you could just change second line in the orginal isValid() method, from $value = $this->getValue(); into $value = $this->getUnfilteredValue();. This way your validation will be performed using unfiltered values.