How can I convert this:
public function rules() {
return [
[['attr1', 'attr2'], 'unique', 'skipOnEmpty' => false, 'skipOnError' => false, targetAttribute' => ['attr1', 'attr2']],
into an inline validator, or what would be the equivalent of this as an inline validator? Thank you.
Is not possible to use Unique validator as ad hoc as explained in https://www.yiiframework.com/doc/guide/2.0/en/input-validation#ad-hoc-validation:
Note: Not all validators support this type of validation. An example is the unique core validator which is designed to work with a model only.
You will have to build it by yourself.
Other way could be to wrap the query into a try catch, assuming that you have a unique key on the db. The db will complain about the query and you can catch the error.
Edit for inline validation:
This is a very specific validator, something you will not reuse so, lets write it inline as an anonymous function:
public function rules(){
[['attr1'], function(){
//we know the names of the attribute so we use them here directly instead of pass as a parameter
if(self::find()->where([
'attr1' => $this->attr1,
'attr2' => $this->attr2
])->exists()){
$this->addError('attr1', 'Error message');
$this->addError('attr2', 'Error message');
}
}]
}
Notice I just registered validation for attr1. If you register also attr2, you will end with 2 errors per each attribute.
Related
So I'm building a form and I need specific fields to be empty.
They return an empty string and from other similar questions, I looked for
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class
in Kernel.php which is commented out by default, I believe.
I don't want to change its behavior since it's a global middleware.
I have tried making them nullable, string|sometimes, present|max:0 yet none of these give me the desired result. I want the validation to pass only if the fields are empty.
Any help will be deeply appreciated.
So as I understood, you want for specific field to be required, if the other field in form is empty? To achieve that, you can use required_without property in Request validation like this:
public function rules()
{
return [
'filed_name' => 'required_without:other_field_name',
];
}
public function messages()
{
return [
'filed_name.required_without' => 'filed_name is required.',
];
}
More on validation on official documentation.
We're trying to have one or another field validated, the second field only shows up when they choose to not fill in the first. So we only need the second field to validate if the first is left empty from them skipping over it.
For context its to checek the make of an appliance, we have a list of brands/makes known to the system but an option to write it manually if yours doesnt show up. But we need to validate that the manual entry field isn't empty, but only if they've skipped over the first list.
'single_item_make' => 'required_if:policy_type,single|required_if:single_item_make_other,',
'single_item_make_other' => 'required_if:policy_type,single|required_if:single_item_make,'
We tried the above and it didnt work, we cant seem to find anything in the docs about checking fields for being empty.
Only one of these two fields will be submitted at a time.
You can not combine the required_if with the required_without in this case, because it conflicts.
In your current code, the first rule on both is:
required_if:policy_type,single
Which requires both fields if policy_type === 'single', if 1 of the fields is empty this validation will fail.
A solution might be to use complex conditional validation, like so:
$v = Validator::make($data, [
'policy_type' => [
'required',
'in:single,x,y', // ?
],
// some other static validation rules you have
]);
// conditional validation based on policy_type === 'single';
$v->sometimes('single_item_make', 'required_without:single_item_make_other', function ($input) {
return $input->policy_type === 'single';
});
$v->sometimes('single_item_make_other', 'required_without:single_item_make', function ($input) {
return $input->policy_type === 'single';
});
This will only check that both can't be empty at the same time and that one field is required when the other one is empty.
However, this will leave the option for the user to fill in both.
If you would want to validate that both can't be empty, but only 1 can be set at the same time (xor), you would have to extend your validator as this does not exist in Laravel.
Put this in your AppServiceProvider's boot() method:
Validator::extendImplicit('xor', function ($attribute, $value, $parameters, $validator) {
return empty($value) || empty(data_get($validator->getData(), $parameters[0]));
});
Then you can use:
$v->sometimes('single_item_make', 'required_without:single_item_make_other|xor:single_item_make_other', function ($input) {
return $input->policy_type === 'single';
});
$v->sometimes('single_item_make_other', 'required_without:single_item_make|xor:single_item_make', function ($input) {
return $input->policy_type === 'single';
});
In this case, required_without makes sure that if 1 is empty the other 1 is required and the xor validation makes sure that if 1 is set, the other 1 can not have a value.
You can add custom error messages in your validation or use a custom validator and pass those validation messages there.
More info: https://laravel.com/docs/5.7/validation#conditionally-adding-rules
I have not tested both pieces of code, but they should work.
As the required_without docs suggest, you need to use it as below:
'single_item_make' => 'required_if:policy_type,single|required_without:single_item_make_other,',
'single_item_make_other' => 'required_if:policy_type,single|required_without:single_item_make,'
I do have a registration form in my laravel 5.4 application and laravel form request validation is used for server side validation. Some fields in this form are populated dynamically using calculations in javascript which need to be validated against user inputs.
The user input fields in the form are 'quantity', 'rate' and 'discount'.
The populated fields are 'total' and 'bill_amount'.
What i need to validate are :
Check 'total' equal to 'quantity' * 'rate'.
Check 'bill_amount' equal to 'total' - 'rate'
I would prefer laravel form request validation methods for this validation. I have tried to use methods like After Hooks and conditionally adding rule etc. and failed.
In simple words the requirement is : check if a field is equal to product of other two fields, and invalidate if not equal and validate if equal.(using form request validation.)
Thanks in advance!
After a long time I was able to find this solution.
Form request After Hooks can be used to achieve the result:
[I was unable to find this logic before]
public function withValidator($validator)
{
$quanty = $this->request->get("quantity");
$rate = $this->request->get("rate");
$billAmount = $this->request->get("bill_amount");
$validator->after(function ($validator) {
if(($quanty * $rate) != $billAmount) {
$validator->errors()->add('bill_amount', 'Something went wrong with this field!');
}
});
}
Does Laravel validation provide any ways to fail when request contains input keys that are not defined in validation rules? Ex: Validator is instantiated with the following rules: ['name' => 'required', 'email' => 'required|email']. I want validation to fail if $request contains any other keys except name and email (Think of a user POSTing to the route end-point with undesirable data). Is that possible to achieve with simple validation rules?
P.S. I am aware of mass-assignment tricks with Eloquent, however I need to perform strict validation before any data is manipulated / persisted.
No, it's not possible to achieve with simple validation rules but would be easy to add.
All you would need to do is something like the following...
if ( count(request()->except(['name', 'email']) ) > 0) {
return false;
}
How can I create a model rule that's only required when a certain value from the Database is 1?
I tried using a 'required', 'when' rule but that doesn't seem to update the client-side JavaScript.
I also tried a custom inline validator but that doesn't seem to post an empty field.
Scenario's aren't an option I think as I have 6 fields and can have any combination of required/not required.
EDIT
At the moment I just never add the required rules, instead of directly returning the rules I store them in a variable. $rules = []
Then before I return the variable I add the required options to the array.
if($x->x_required)
$rules[] = ['your-field', 'required', 'on' => 'your-scenario'];
This is a quickfix and I don't really like it, but it works. I'm not sure if there is a better way of doing this.
You need to use combination required with when, but for client side validation you need additionally specify whenClient property.
Example (add this to your rules()):
[
'attributeName',
'required',
'when' => function ($model) {
return $model->country == Country::USA;
},
'whenClient' => function (attribute, value) {
return $('#country').value == 'USA';
},
],
Official docs:
RequiredValidator
Validator $when
Validator $whenClient