Laravel Validation sometimes rules for date validation - laravel

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.

Related

Use `trans_choice()` in request validation messages with validation rule parameter

I need a request validation rule to return a custom message upon failure, and since the field being validating is an array with a min:x rule i'd like to have a custom message for both singular and plural variations.
I'm just wondering how to pass to the trans_choice() function the :min parameter from the validation rule:
Translation file:
'array' => [
'field' => [
'min' => 'You need to select at least one item.|you need to select at least :min items',
],
],
Request message() method:
public function messages() {
'my.array.field.min' => trans_choice('translations::array.field.min', ???),
}
It seems like there's nothing built into Laravel to use trans_choice whenever you can pluralise a translation string.
A way you could solve that is by temporarily (or permanently, whatever fits your use-case) changing the replacer for the min rule to something like this:
Validator::replacer('min', function ($message, $attribute, $rule, $parameters, $validator) {
$minValue = $parameters[0];
$message = Str::contains($message, '|')
? trans_choice($message, $minValue)
: $message;
return str_replace(':min', $minValue, $message);
});
Or by extending the Validator factory to work in your favour, but since that requires you to change many of it's methods I don't really recommend that.

Laravel Custom validation rule with parameters

I have write this function rule in CustomRequest to check checkHackInputUser rule that define in provider:
Actually i want to check the value that pass in route
for example :
http://www.somedomain.com/user/{id}
I what do some operation on this $id variable
with my checkHackInputUser rule
Here is CustomRequest:
public function rules()
{
$request_id = $this->route('user');
$rules = [];
if($this->method() == "DELETE" || $this->method() == "GET" )
$rules = [
'role_list' => 'required|checkHackInputUser:'.$request_id,
];
return $rules;
}
The problem is,this rule(checkHackInputUser) doesn't work if i remove required role.
Here is the checkHackInputUser validation function in provider:
public function boot()
{
$this->app['validator']->extend('checkHackInputUser',function($attr,$value,$params){
//Some validation
return false or true;
});
}
You can conditionally validate input when present using sometimes.
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email',
]);

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;
}

Check if field exists in Input during validation using Laravel

I want to make sure that certain fields are posted as part of the form but I don;t mind if some are empty values.
The 'required' validation rule won't work as I am happy to accept empty strings. I have tried the below, but as the 'address2' field is never sent, the validator doesn't process it.
Any ideas?
$rules = array(
'address2' => 'attribute_exists'
);
class CustomValidator extends Illuminate\Validation\Validator {
public function validateAttributeExists($attribute, $value, $parameters)
{
return isset($this->data[$attribute]);
}
}
You can use Input::has('address2') to check if something is posted by address2 input name. See the example:
if(Input::has('address2')) {
// Do something!
}
In Laravel 5,
if($request->has('address2')){
// do stuff
}
You should make custom validator like this.
use Symfony\Component\Translation\TranslatorInterface;
class CustomValidator extends Illuminate\Validation\Validator {
public function __construct(TranslatorInterface $translator, $data, $rules, $messages = array())
{
parent::__construct($translator, $data, $rules, $messages);
$this->implicitRules[] = 'AttributeExists';
}
public function validateAttributeExists($attribute, $value, $parameters)
{
return isset($this->data[$attribute]);
}
}
This will make AttributeExists work without to use require. For more explain about this. When you want to create new validator rule. If you don't set it in $implicitRules, that method will not work out if you don't use require rule before it. You can find more info in laravel source code.
When you submit a form each and every field is posted, matter of fact is if you leave some filed empty then that field value is null or empty. Just check the POST parameters once, to do so open the firebug console in firefox and submit the form, then check the post parameters. As you want to accept empty string what is the use of any rule?
else You can do this
$addr2=Input::get('address2');
if(isset($addr2)){
//do here whatever you want
}else{
//do something else
$addr2='';//empty string
}
Actually, Laravel has a method to validate if an attribute exists even if not filled.
$rules = [
'something' => 'present'
];
All the validation rules are stored in Validator class (/vendor/laravel/framework/src/Illuminate/Validation/Validator.php), you can check for the implementation of each rule, even no documented rules.

Resources