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

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',

Related

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

Make http/https optional in laravel validation

When I use laravel url validation rules like:-
array(
'name' => 'required|min:3',
'url' => 'required|url'
)
It rejects any url that does not have http:// or https://. However I would like to make it optional.
You can just ignore the url rule. Or you need to prefix your input.
Another way is to set an custom rule.
If you use url rule, http(s):// is mandatory, because the part that makes a URI a URL is the inclusion of the "access mechanism", which is what http:// or ftp:// is for.
You should consider custom rule perhaps or some logic that would add http:// to validated value if you detect no "access mechanism" part present.

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.

cakephp url validation

One of my models has a 'url' field. I am using the default url validation rule on it. When trying to add a specific url it is not validated.
The url causing validation to fail is http://careers2.hiredesk.net/ViewJobs/JobDetail.asp?Comp=I3&TP_ID=1&PROJ_ID={BDA01FCD-5703-4D40-9197-CCF688633951}
The { character is causing the validation to fail. What workarounds do I have here?
Do you pass your given URL through a URL Encode Function first? See the linked page for an example.

Resources