Validate only if the field is entered in Laravel 5.2 - validation

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.

Related

Laravel validation numeric with gte:1 throws exception

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

Laravel validation rules - how optional, but only if another condition is true

How can I make a custom rule using Validation, so that the field can be nullable 'since' call function the result is true, otherwise, the field becomes required.
Of course I tried to use the 'nullable', but even if the field is empty, the Validation should execute the checkAreasDiff() function to validate that the field can be empty during the update.
In my controller, I created a function:
private function validator_update(array $data) {
\Validator::extend('areas_diff', function($attribute, $value, $parameters, $validator) {
return checkAreasDiff();
}, 'VALIDATOR AREAS_DIFF OK.');
/**
* RULES
*/
$rules = [
'fiscalizoarea' => 'areas_diff',
];
/**
* Return \Validator
*/
return \Validator::make($data, $rules, $msgs);
}
If I understand the question correctly, you want one field to be required only if another is not null?
There is a Laravel rule for that already: required_with.
required_with:foo,bar,...
The field under validation must be present and not empty only if any
of the other specified fields are present.
Or, if I'm getting your logic back to front: required_without
required_without:foo,bar,...
The field under validation must be present and not empty only when any
of the other specified fields are not present.

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

YII2 validation check unique between two fields without using active record

I am using two fields "old_password" and "new_password". I want the error message if value in both fields are same.
I am not using Activerecords.
I tried in model :
['a1', 'unique', 'targetAttribute' => 'a2']
but above code will work only for active record.
How can i get error message without using active record ?
You need to use compare validator instead of unique.
['new_password', 'compare', 'compareAttribute' => 'old_password', 'operator' => '!='],
Because unique validator validates that the attribute value is unique across the table
If your model extend yii\base\Model, activeRecerd are not necessary and you can use the rules function
public function rules()
{
return [
['a1', 'unique', 'targetAttribute' => 'a2'],
];
}
for assign your validation rules
and in your controller you can perform validation invoking $model->validation
$model = new \app\models\YourForm();
like suggested in Yii2 guide for validating input
// populate model attributes with user inputs
$model->load(\Yii::$app->request->post());
// which is equivalent to the following:
// $model->attributes = \Yii::$app->request->post('ContactForm');
if ($model->validate()) {
// all inputs are valid
} else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}

Resources