Laravel validation numeric with gte:1 throws exception - laravel

Why Laravel throws
InvalidArgumentException('The values under comparison must be of the same type');
exception, when input non-numeric text like 'test' on rule:
public function rules()
{
return [
'account_no' => 'required|numeric|gte:1'
];
}
When expected just not to pass validation and display message:
account_no field must be numeric
How to solve this exception?

Merdan the field under gte validation must be greater than or equal to the given field. The two fields must be of the same type.
example let's say you have two fields
POST DATA
// $request->comparison = 1;
// $request->account_no = 20319312;
your rules should be something like
return [
'account_no' => 'required|numeric|gte:comparison'
];

You have to use gte, the gt and gte are added in Laravel 5.6 and latest versions and I'm not sure what laravel version you are using.
I think you can try like this:
public function rules()
{
return [
'account_no' => 'required|numeric|min:1'
];
}
OR
public function rules()
{
return [
'account_no' => 'required|numeric|min:0|not_in:0'
];
}
The min:1 is the minimum value of 1 and no negative values are allowed
The not_in:0 is the value cannot be 0.
Also you can also use regular expression for doing this job.
I hope it would be helpful. Thanks

Related

Laravel Validation sometimes rules for date validation

I currently have a validation rule which looks like this:
public function rules()
{
return [
'startDate' => 'required|sometimes|before_or_equal:endDate',
'endDate' => 'sometimes|required|after_or_equal:startDate',
];
}
The sometimes option works as I understand it on the basis that if the field is present, run the validation rule. However, if the end date is not sent or is null, my before or equal rule kicks in and fails. In some instances within my application, end date will be null. Is there a way to 'cancel' the startDate validation rule in this instance or would I need to create a custom validator for this purpose?
something like before_or_equal_when_present ?
You can use IFs to add and manipulate rules in the rules function. You can access the inputs there referring to $this as the request itself:
public function rules()
{
$rules = [
'startDate' => 'required|sometimes|before_or_equal:endDate',
'endDate' => 'sometimes|required|after_or_equal:startDate',
];
if( $this->input('endDate') > 0)
$rules['endDate'] = "rule". $rules['endDate']
return $rules;
}
This is just a mockup just to let you know that you can manipulate and have access to the fields passed.

Laravel validation rule "URL" does not pass empty value

I have input text field whith validation rule :
public function rules()
{
return [
'field' => 'url',
];
}
It`s not required (field can be empty) but validation return an error.
Solve problem use "nullable":
public function rules()
{
return [
'field' => 'nullable|url',
];
}
Add sometimes rule to the validation. This means to validate it for a URL when the value is not given or null.
public function rules()
{
return [
'field' => 'sometimes|url',
];
}
when we submmitting values from js, like through a FormData, the value null could be submitted as string containing 'null', which may pass a nullable rule, cause further type check fail. so be sure to make this value be posted as '', literaly nothing, no a 'null' string
When you use formData (js) to submit your request, "null" is assigned by default for all empty fields. This will pass through Laravel "nullable" validaton and indicate as invalid input. So, please, use something like below in your validation rules.
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [];
if($this->filled('field') && $this->field!= 'null'){
$rules['field'] = 'url';
}
return $rules;
}
In order to do this use laravel's form requests. https://laravel.com/docs/8.x/validation#creating-form-requests

Change date format before validation

I have to change the date format before validation.
I use the german date format (dd.mm.yyyy). But for the validation i need the format yyyy-mm-dd.
here my rules from the requests file:
public function rules()
{
return [
'title' => 'required|min:5',
'start' => 'required|date_format:d.m.Y|after:+1 week|unique:talks,start',
'end' => 'required|date_format:d.m.Y|after:start|unique:talks,end',
'interval' => 'required'
];
}
Now i found this function:
public function all()
{
$input = parent::all();
//modify input here
return $input;
}
But how can i modify the input here???
Thanks for your help
The $input variable is just an associative array with key -> value pairs of the request input. You can directly modify the array:
public function all()
{
$input = parent::all();
$input['start'] = date("Y-m-d", strtotime($input['start']));
$input['end'] = date("Y-m-d", strtotime($input['end']));
return $input;
}
This will translate your date values for the purposes of validation. Because the validator calls the all() method.
However, this does not modify the original values in your input.
Whenever you access the input values by a different method than all(), the original value will appear. E.g. $request->input('start') will give you the original German format but $request->all()['start'] will give you the translated international formal.
Such a situation is a potential source of bugs and it's hard to maintain. The right solution for your problem is to write a tiny custom middleware that will modify the request values. See here: https://laracasts.com/discuss/channels/general-discussion/laravel-5-modify-input-before-validation?page=2

Yii2 compare email without case sensitive

I use the simple compare validation rule offered by Yii2 like this:
[confirm_email', 'compare', 'compareAttribute'=>'email', 'message'=>"Emails don't match"],
The problem is that this rule compares two emails 100% including Case Sensitive which means email#test.com and email#Test.com will generate validation error.
Is there a way to remove this Case Sensitive comparison from this rule?
strcasecmp does not handle multibyte characters, read this
suggestion is to use strtolower()
you might also be interested in yii's input filter, to transform input to lowercase, like this:
[
// both email fields tolower
[['email', 'confirm_email'], 'filter', 'filter' => 'strtolower'],
// normalize "phone" input
['phone', 'filter', 'filter' => function ($value) {
// normalize phone input here
return $value;
}], ]
You can create custom validation if you want.
public function rules()
{
return [
// an inline validator defined as the model method validateEmail()
['email', 'validateEmail'],
];
}
public function validateEmail($attribute, $params)
{
if (strcasecmp($this->attribute, $this->confirm_email) == 0) {
$this->addError($attribute, 'Username should only contain alphabets');
}
}
It will compare emails with binary safe case-insensitive.

Validate only if the field is entered in Laravel 5.2

public function rules() {
return [
'num_of_devices' => 'integer'
];
}
I want to validate an integer field if and only if the field is entered. But above rule validates it for integer even if the field is empty. I used somtimes, but no result. But when I var_dump($num_of_devices) it is string.I am using Laravel 5.2. I think It was working fine in 5.1.
From version 5.3 you can use nullable
public function rules() {
return [
'num_of_devices' => 'nullable | integer'
];
}
Add a rule to array, if input is not empty. You could collect all your validation rules to $rules array and then return the array.
if( !empty(Input::get('num_of_devices')) ){
$rules['num_of_devices'] = 'integer';
}
You’re looking for the sometimes validation rule. From the documentation:
…run validation checks against a field only if that field is present in the input array.

Resources