Avoiding form validation enforced checks on non-required fields in CodeIgniter - 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.

Related

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.

Laravel validator vs requests

Hello,
I want to understand how to handle data validation with Laravel 5. I see that this can be done using or the validator, or the request files. The thing is that there are many points I didn't get.
What is the difference between using a request file for validation or the validator class ?
If I have validation conditions, and I want to use them only if the concerned field was submitted, how can I do that ? If I use the "required" keyword, it won't work because it will fail when the field is not submitted. If I don't use it, it will accept empty strings...
Thanks ahead !
1. Theoretically there is no difference between Controller validation and Validation using FormRequest. Normally you should use FormRequest. This will keep your controller clean and Minimal. But some time it is sensible to use Validator within controller, e.g you know there is going to be just one field to validate, then it would be overkill to use FormRequest. So it is a matter of preferance.
2. You don't have to use 'required' if the field is not required. Other validation for that field will still run if that field is submitted. If not submitted nothing will happen.
.......
'money' => 'numeric',
.......
Above Rule will make sure that money field is numeric only if it is submitted. If no submitted no validation error will be thrown.
I hope this helps.
Request classes are the better way to validate requests, because
they help to extract this functionality from the constructor method,
which should be as clean as possible.
Use 'sometimes' validator. http://laravel.com/docs/5.1/validation#conditionally-adding-rules

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

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

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.

Codeigniter Form Validation : order of validation rules

I have a form validation rule of something like this
$this->form_validation->set_rules('name', 'Name', 'trim|required|strip_tags|xss_clean|callback__name_check');
Now if anyone enters <p></p> or equivalent (empty tags), the result will be empty, but somehow required rule will pass as well, resulting in blank name when inserting to database.
I can do an extra check before inserting, but I wonder if there's a way in CI to prevent that?
Thanks
Have you tried to switch required and strip_tags in this rule?
$this->form_validation->set_rules('name', 'Name', 'trim|strip_tags|required|xss_clean|callback__name_check');
Try to delete the strip_tags rule (not appear in the codeigniter user guide) and try with:
$this->form_validation->set_rules('name', 'Name', 'trim|required|prep_for_form|xss_clean|callback__name_check');
I think that this is usefull for you
User guide says:
prep_for_form
Converts special characters so that HTML data can be shown in a form field without breaking it.
http://codeigniter.com/user_guide/libraries/form_validation.html

Resources