I have a multiple fields binded to "x-editable" plugin that sends the changed data and like all of the data, I want to validate them.
But the problem here is that it always sends just 2 fields: name=is_on_probation&value=1. Here, the name key is the field that must be validated (it is the same as DB column) and a value is pretty self-explanatory.
I've written a validation rule like this:
'is_on_probation' => 'sometimes|...'
But then I realized that it won't be validated, because the actual subject of validation is in the value field.
So, the question here is: how can I validate the value field and apply the corresponding rule, accordingly to the name value?
I created this logic in order not to pollute the controller with additional arrays and logic, so it is going to save only the passed parameter.
Kinds regards!
P.S. I've searched for the StackOverflow, but did not find the question that describes my problem the best. May be I am wrong and did not see it.
Update
After thinking a bit, I cam up with the solution to use switch and pass the request field there, like this:
switch($this->request->get('name')) {
case "email":
$rules = [
'value' => 'sometimes|required|unique:users,email|email:rfc',
];
break;
case "phone":
$rules = [
'value' => 'sometimes|required|min:8|max:13|regex:/^(\+371)?\s?[0-9]{8}$/'
];
break;
}
$rules[] = [
'pk' => 'required|exists:users,id'
];
The question is still in place, however - is it the best solution and a good practice to do so?
Try to merge your data into the request before starting validation.
$request->merge([$request->input('name') => $request->merge([$request->input('value')]);
Then your validation
'email' => 'sometimes|...','phone' => 'sometimes|...',
Related
There is the situation when i have to validate some form's field certain way depend on which value contains in other form's field.
E.g.
$rules = [
// Bot's setup
"settings.setup.auto_end" => ["required", "boolean"],
// Auto end's time in case of using contest auto ending
"settings.additional.auto_end.type" => ["required_if:settings.setup.auto_end,1", "integer"],
"settings.additional.auto_end.time" => [
"required_if:settings.setup.auto_end,1",
"required_if:settings.additional.auto_end.type,0",
"date_format:U",
"after:now"
],
"settings.additional.auto_end.time" => [
"required_if:settings.setup.auto_end,1",
"required_if:settings.additional.auto_end.type,1",
"cron_time"
],
];
settings.additional.auto_end.time may being validated different ways. In what way exactly, as i see it, depend on settings.additional.auto_end.type field.
In case when settings.additional.auto_end.type == 0, settings.additional.auto_end.time is validated for proper unix timestamp value.
When settings.additional.auto_end.type == 1, settings.additional.auto_end.time must be validated for custom validation rule cron_time.
But each time when i validate request form by this FormRequest implementation, settings.additional.auto_end.time is being validated by second rule.
This caused by that settings.additional.auto_end.time's second validation rule override previous rule. To my mind, it's not obvious behavior. But i understand that this behavior is based on php's array implementation.
Is there a more clear and convenient method to validate form value by certain rule which select based on some condition?
Maybe there is some switch validation rule?
The first thing that comes to mind, is to implement this logic in new custom validation rule.
But in this case of implementation the validation rules are hard-coded in custom validation rule.
I'm validating question and answers (for test creation). I'd like to ensure that the answers array contains at least one 'correct' item. So where answers.*.correct => true.
I currently have the following:
public function rules()
{
return [
'title' => 'required|string|max:255',
'test_id' => 'required|integer|exists:tests,id',
'content' => 'required',
'answers' => 'required|array',
'answers.*.text' => 'required|string|max:255',
'answers.*.correct' => 'required|boolean'
];
}
At the moment i can miss out adding a correct answer causing an impossible question.
I've checked the documentation and can't see anything that stands out.
Any help would be appreciated.
EDIT ANSWER
I used this (as the answer mentions): Laravel validate at least one item in a form array
I managed to create a custom rule like so:
public function passes($attribute, $value)
{
foreach ($value as $arrayElement) {
if ($arrayElement['correct'] == true) {
return true;
}
}
return false;
}
Then in my existing rules() section for the request I added in the new rule i created:
'answers' => ['required', 'array', new ArrayAtLeastOneBoolTrue()],
You are here validating that the array answers has:
A string with max. 255 chars (text)
A boolean (correct)
To check the completeness of this array, the Laravel request is the wrong place to check. Technically it would be possible to create your own validation rule, but makes no sense here. Instead you should iterate this array in your controller and verify the completeness of each answers.
Two more ideas, to do it better:
Don't send all answers and if they were answered correctly in one single array. Instead, send the selected answer to your api with a single request per answer at the moment the user clicks it. This will 1. prevent that somebody can send you the information that he answered 100% correct (not good if this is a school software :) ) and 2. depending on how much questions there are it will reduce the data sent to the server to a minumum, mainly because...
... it seems you send the whole text of the question to the server to identify the answer. Use a unique ID per question and send it as question ID + the selected or entered answer.
EDIT: Thanks for the comments, sorry for my misunderstanding here. As mentioned above then of course custom validation makes totally sense here to check per question if at least one answer is correct. Check this out: https://stackoverflow.com/a/53791208/2264877
how could one make the following validation:
something like exclude_if:field,value
The field under validation cannot be present if the field "field" is equal to value.
I thought of doing a custom validation, but I am not sure how to pass the value of the other field into the custom validation class.
A real world example for this case would be if we have let's say two checkboxes A and B, and we want to make sure that if A is checked then B cannot be checked.
Anybody? Thanks!
Laravel has this covered out of the body. Lets say you don't want additional_field to be required to be filled in if the field is greater than the value 100.
Firstly - do your static rules that never change:
$v = Validator::make($data, array(
'name' => 'required',
'field' => 'required|numeric',
));
Then you can validate a sometimes rule against the field rule:
$v->sometimes('additional_field', 'required, function($input)
{
return $input->field > 100;
});
You can read more about conditionally adding rules in the Laravel Docs here.
I was investigating CakePHP (2.3.4) Model::save method to insert new records and ran into a little snag:
//Two fields provided, email field intended to fail validation
$data = array('Member' => array(
'username' => 'hello',
'email' => 'world'
));
$this->Member->create();
var_dump($this->Member->save($data, true));
The above save() will return false and no data will be written to the database. However if I change the data to:
//One field provided, intended to pass validation
$data = array('Member' => array(
'username' => 'hello'
));
then save() will attempt to write a new record to database with a blank email field. I realize that skipping validation for unspecified fields might be a useful behavior during updates, but is there a CakePHP recommended way to handle partially empty data sets when creating new records? Thanks a lot.
Edit:
Thanks to Sam Delaney for the tip. In case anybody else gets stumped, this did the trick: CakePHP Data Validation: field 'required' key
This key accepts either a boolean, or create or update. Setting this key to true will make the field always required. While setting it to create or update will make the field required only for update or create operations. If ‘required’ is evaluated to true, the field must be present in the data array. For example, if the validation rule has been defined as follows:
I had originally baked the model and forgotten that required => true was left out of the validation rule. Setting it to true or 'create' would've avoided me blank records getting inserted due to gibberish data array.
IMHO what you've experienced is the desired behavior. Consider that you have the same two fields within a form and the user provides a value for only username. Both username and email field are submitted even though email is empty. Then on the server, you try to save the record only to find out that it has failed validation which you feedback to the user. On the other hand, perhaps in your system it is perfectly possible to create a user without requiring an email (for example root access account), CakePHP's validation implementation allows both of these scenarios.
If this flexibility isn't what you desire, just set the required attribute for your validation rule as true:
public $validate = array(
'email' => array(
'rule' => 'email',
'required' => true
)
);
This will satisfy your all or nothing requirement.
I've done quite a few Lithium tutorials (links below in case they help someone else, and also to show I've done my homework:) and I understand the most basic parts of creating models, views, controllers and using MVC to create a DB record based on form input.
However, I'm new to MVC for webapps and Lithium, and I'm not sure how I should write my code in more complicated situations. This is a general question, but two specific validation questions that I have are:
How should I validate date data submitted from the form?
How should I check that the two user email fields have the same value?
I would be very grateful for any help with these questions, and concrete examples like this will also really help me understand how to do good MVC coding in other situations as well!
Date entry - validating data split across multiple form inputs
For UI reasons, the sign up form asks users to enter their DOB in three fields:
<?=$this->form->field('birthday', array('type' => 'select', 'list' => array(/*...*/))); ?>
<?=$this->form->field('birthmonth', array('type' => 'select', 'list' => array(/*...*/))); ?>
<?=$this->form->field('birthyear', array('type' => 'select', 'list' => array(/*...*/))); ?>
What is the best way to validate this server-side? I think I should take advantage of the automagic validation, but I'm not sure of the best way do that for a set of variables that aren't really part of the Model. E.g.:
Should I post-process the $this->request->data in UsersController? E.g. modify $this->request->data inside UsersController before passing it to Users::create.
Should I pull the form fields out of $this->request->data and use a static call to Validator::isDate inside UsersController?
Is there a way to write a validation rule in the model for combinations of form variables that aren't part of the model?
should I override Users::create and do all the extra validation and post-processing there?
All of these seem like they could work, although some seem a little bit ugly and I don't know which ones could cause major problems for me in the future.
[EDIT: Closely related to this is the problem of combining the three form fields into a single field to be saved in the model]
Email entry - checking two form fields are identical, but only storing one
For common sense/common practice, the sign up form asks users to specify their email address twice:
<?=$this->form->field('email_address'); ?>
<?=$this->form->field('verify_email_address'); ?>
How can I write an automagic validation rule that checks these two form fields have the same value, but only saves email_address to the database?
This feels like it's pretty much the same question as the above one because the list of possible answers that I can think of is the same - so I'm submitting this as one question, but I'd really appreciate your help with both parts, as I think the solution to this one is going to be subtle and different and equally enlightening!
[EDIT: Closely related to this is the problem of not storing verify_email_address into my model and DB]
Some background reading on Lithium
I've read others, but these three tutorials got me to where I am with users and sign up forms now...
Blog tutorial
Extended blog tutorial
MySQL blog tutorial
Some other StackOverflow questions on closely related topics (but not answering it and also not Lithium-specific)
One answer to this question suggests creating a separate controller (and model and...?) - it doesn't feel very "Lithium" to me, and I'm worried it could be fragile/easily buggy as well
This wonderful story convinced me I was right to be worried about putting it in the controller, but I'm not sure what a good solution would be
This one on views makes me think I should put it in the model somehow, but I don't know the best way to do this in Lithium (see my bulleted list under Date Entry above)
And this Scribd presentation asked the question I'm hoping to answer on the last page... whereupon it stopped without answering it!
NB: CakePHP-style answers are fine too. I don't know it, but it's similar and I'm sure I can translate from it if I need to!
I'd recommend doing this in the Model rather than the Controller - that way it happens no matter where you do the save from.
For the date field issue, in your model, override the save() method and handle converting the multiple fields in the data to one date field before calling parent::save to do the actual saving. Any advanced manipulation can happen there.
The technique described in your comment of using a hidden form field to get error messages to display sounds pretty good.
For comparing that two email fields are equal, I'd recommend defining a custom validator. You can do this in your bootstrap using Validator::add.
use lithium\util\Validator;
use InvalidArgumentException;
Validator::add('match', function($value, $format = null, array $options = array()) {
$options += array(
'against' => '',
'values' => array()
);
extract($options);
if (array_key_exists($against, $values)) {
return $values[$against] == $value;
}
return false;
});
Then in your model:
public $validates = array(
"email" => array(
"match",
"message" => "Please re-type your email address.",
"against" => "email2"
)
);
Edit: Per the comments, here's a way to do custom rule validation in a controller:
public function save() {
$entity = MyModel::create($this->request->data);
$rules = array(
"email" => array(
"match",
"message" => "Please re-type your email address.",
"against" => "email2"
)
);
if (!$entity->validates($rules)) {
return compact('entity');
}
// if your model defines a `$_schema` and sets `$_meta = array('locked' => true)`
// then any fields not in the schema will not be saved to the db
// here's another way using the `'whitelist'` param
$blacklist = array('email2', 'some', 'other', 'fields');
$whitelist = array_keys($entity->data());
$whitelist = array_diff($whitelist, $blacklist);
if ($entity->save(null, compact('whitelist'))) {
$this->redirect(
array("Controller::view", "args" => array($entity->_id)),
array('exit' => true)
);
}
return compact('entity');
}
An advantage of setting the data to the entity is that it will be automatically prefilled in your form if there's a validation error.