How to handle context specific fields and fieldsets / context specific input validation in an Apigility driven Zend Framework 2 application? - validation

In the Zend Framework 2 application I'm currently developing with Apigility there is a resource address, that provides following access points:
GET /address
id <-- required
PATCH /address
id <-- required
street
zip
city
type
OK. Now I started implementing a futher one for inserting items:
POST /address
street
zip
city
type
Since in the context of the POST method the id is not needed, it hence cannot be required. The problem is, that in Apigility there is no context dependent fields / fieldsets (yet?). So in order to implement the POST method, I have to make the id field not-required for all methods. But then I have to make them required for GET and PATCH manually (yet don't know how).
Is it possible to define context dependent fields / fieldset in Apigility? (Maybe I simply didn't find this option.)
If not: Which approaches are there to handle this?

Apigility does support verb specific validators. Validators are only applied or needed on POST, PUT and PATCH though. DELETE and GET do not take any body and that's the only part of a request that Apigility supports validation on.
Additionally, it's probably unlikely that you want the user of your API to supply the id. This is pretty rare. As you've indicated in POST, the id would likely be generated. This means also that the id would be provided for PUT and PATCH, but it should be part of the URL.
For example:
PUT /address/4
PATCH /address/5
In your route, you should have something like /address[/:id]. Based on whether or not this id is provided will determine what method is called in your resource class. PUT without the id (PUT /address) would call replaceList, while PUT with the id would call update. PATCH with an id calls the patch method. It doesn't really make sense to have PATCH without an id.
If you want to constrain the values in the URL, you can add a constraints section to the route's options like so:
'router' => array(
'routes' => array(
'your-api.rest.address' => array(
'type' => 'Segment',
'options' => array(
'route' => '/address[/:address_id]',
'defaults' => array(
'controller' => 'YourApi\V1\Rest\Address\Controller',
),
'constraints' => array(
'address_id' => '[0-9]+',
),
),
),
),
),
)
The key for constraints should match the name of the id variable in your route. The value would be a regular expression that matches the possible legitimate values for the id. You don't include regex delimiters for this. It will make requests to something like /address/banana return a 404 and the request will not make it into your resource's code.
With this in place, I'd recommend removing the id field from your fields list. You'll likely be able to use the same set of validators for POST, PUT and PATCH. It's important to understand how the validators are applied depending on the verbs as well.
In all the verbs, if you've configured filters, those will be applied to the supplied fields before validation. This means, for instance, if you have a filter of \Zend\Filter\Digits, then all non-digits will be removed prior to validation. If your validator is something like \Zend\Validator\Digits, then as long as the field contains at least one digit, it will be valid.
There are slight differences in how the validators are applied based on verbs. In POST and PUT (with an id in the URL), you can include extra fields that are not specified in your validators. In PATCH, there will be an error if you send in any fields which are not specified in the validators.
For PUT without an id (routing to replaceList), the expected body will be an array of objects.
The final caveat with the validators is that if you have filters applied to any fields and the validation passes, the values in $data that are passed into any of the methods will be the values before filtering is applied. Going back to the earlier example with a field that has the Digits filter and the Digits validator, if you send in something like {'my_field': '1234banana56'}, it will pass the validation but the value in $data will not be 123456, it will be 1234banana56. If you want to get the filtered value, you need to do something like this:
$filteredData = $this->getInputFilter()->getValues();
This will give you back an array of the filtered and validated field values. Any fields that were not specified in your validator will not be returned in this array. There has been talk about making this behavior configurable so that $data would receive the filtered data values, but as of this writing, that's how it works.
If you do find that you need different validators based on different verbs, the answers are in the docs here: https://apigility.org/documentation/content-validation/advanced
Hope this all helps.

Related

Laravel validation not required but still comes back as if it is required

Having some slight issues with laravel validation rules. I.e. I have setup a form with a field name of 'url'. This url needs to be a URL but is not required.
So I have:
'url' => 'url',
In the validation rules, but it still comes back on submit that the URL is an invalid format. But I didn't fill it out and it isn't required.
Slightly confused here, anything I should look out for here?
https://laravel.com/docs/5.6/validation#a-note-on-optional-fields
By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid.
So, this validation rule will do the trick:
'url' => ['nullable', 'url']
For that, I usually use nullable in the very beginning
'url' => 'nullable|url',

How to share validation rules of several models and a large ajax form that holds them

I have a large ajax managed form with several steps. Obviously, I need to validate data after each submit step. The final validation results in the creation of several business objects.
Some business objects will receive all of their fields, others will not. For example, the customer who will not receive the billing address (it will be requested at the time the billing takes place). Indeed, the form being very long, I do not want to overload it by adding elements not immediately useful.
Some form partial concern only few informations
hold by my model so i can't instanciate model just for validation of little % of his attributes.
In principe, with October, the validation is done at the level of the models by adding the trait validator which will make it possible to use the generic Laravel validation functionalities (perhaps i'm wrong here)
But I'm not sure I can use on the models validation because some will be incomplete at the end of the form filling.
It is necessary to mutualize the validation of all these data without making a gas factory with duplicate validation code but how, where?
For the moment I am on the idea of ​​making a trait added to my object component which handles all my ajax handlers but I am not excited because it does not correspond to my idea to mutualize the validation
Perhaps using behavior instead of traits are better
https://octobercms.com/docs/services/behaviors
to be continued ...
If I had to do it, I'll use the Validation service after each submit step.
https://octobercms.com/docs/services/validation
You can store the info in a session and use them at the final stage.
$myinput = post('myinput');
$validator = Validator::make(
[
'myinput' => $myinput
],
[
'myinput' => 'required|min:8'
]
);
if ($validator->fails()) {
// The given data did not pass validation
}
// store in session
Session::push('myform.myinput', $myinput);
Session::push('myform.step', 2);
PS: on est deux francophones qui se causent en anglais :)

Laravel - Customize :attribute value?

I have a page with 2 forms. Since the id attribute of HTML elements must be unique, I prefixed my ids with login_ and register_. I'm using Request objects to handle those requests : I made a LoginRequest and a RegisterRequest, and set the rules in the rules() method.
However, when printing the errors, I know have a message like :
The login email field is required.
Is there any way I can tell Laravel that even if the id of my input is login_email, I would like him to print email (i.e. without the prefix) ? I know I can return custom messages by implementing the messages() method, however I would like to avoid doing that, since the default messages are good for me, just the value of the :attribute object that makes the error message a bit hard to understand.

Validation for file types not working in laravel 4

After lots of search and no luck to found the solution.
I am validating a input file in laravel 4.2.*. Using the model validation rules but rules not working for me.
rules i am using in my model.php
'reqfile' => 'mimes:txt,pdf,doc,docx|max:20000'
and
'reqfile' => 'mimes:application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain,application/pdf|max:20000'
After applying these rules the validation errors generated but the errors also appear on the valid file selection.
Here's anybody tells me, where i am wrong to apply the rules.
Thanks in Advance.
For this validator rule to work you need to make sure that the value being validated for reqfile is an instance of:
Symfony\Component\HttpFoundation\File\File
or
Symfony\Component\HttpFoundation\File\UploadedFile
So if you're validating a form, reqfile must be a uploaded file. That means its value should come from Input::file(). So your validator should look something like this:
Validator::make(
// Value for reqfile
array('reqfile' => Input::file('reqfile')),
// Validator rule for reqfile
array('reqfile' => 'mimes:txt,pdf,doc,docx|max:20000')
);
The validation rule will actually try to guess the extension by extracting the mime type and compare that to the extension list passed into the rule. That means that you need to pass file extensions to the rule, not actual mime types, as the documentation clearly states:
The file under validation must have a MIME type corresponding to one of the listed extensions

Avoiding form validation enforced checks on non-required fields in CodeIgniter

I have an e-mail field which is -not- required in my form validation. It should be able to be left blank. However, when I use the "valid_email" parameter of the form validation's set_rules, it still gives an error message that the e-mail is not valid when it's not supposed to check this if the field has not been filled out.
Rule Reference
Checking the reference on this matter tells us the following regarding the valid email rule:
Returns FALSE if the form element does not contain a valid email address.
This would be true of an empty field, as well as a field with bad values.
Trimming
I notice in the examples provided by CodeIgniter that emails are usually not only required, and required to be valid emails, but are also trimmed. This may result in a different outcome.
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
During the validation process, the following is considered:
// If the field is blank, but NOT required, no further tests are necessary
if ( ! in_array('required', $rules) AND is_null($postdata))
It may be the case that the contents of your email field aren't exactly null, and are therefore raising flags with the valid_email requirement.
Possible Related Bugs
Three months prior to the date of this answer there was discussion on bitbucket regarding this very topic. The discussion can be viewed at https://bitbucket.org/ellislab/codeigniter-reactor/issue/117/input-fields-are-automatically-required.
It's stated that using array-syntax (see below) in the markup results in similar errors even when the required rule is not set:
<input name="user[email]" />
Further discussion, and patches, are available here, http://codeigniter.com/forums/viewthread/159243. One suggest patch that seems to solve the issue is to replace the is_null() call with empty() in the aforementioned code:
So the following:
if ( ! in_array('required', $rules) AND is_null($postdata))
Becomes:
if ( ! in_array('required', $rules) AND empty($postdata))
according to https://codeigniter.com/user_guide/libraries/validation.html?highlight=validation#id28
use permit_empty this
Allows the field to receive an empty array, empty string, null or
false
so your code looks like this:
$this->form_validation->set_rules('email', 'Email', 'permit_empty|valid_email');
You just have to appreciate that '' IS not a valid e-mail address. If you don't want to validate some postdata and don't care if it's empty, you shouldn't set a rule on it, like so:
if($this->input->post('item'))
{
$this->form_validation->set_rules('item', 'Item number', 'trim|alpha_numeric|max_length[30]');
}
In this case, if there is nothing submitted for 'item', no rule is added, so the rest of the data would go on to validation stage etc. as normal.

Resources