I have a model like so
class Person extends yii\db\ActiveRecord
{
public $desk_no;
public $mobl_no;
public $faxx_no;
}
I want to add a validation rule which would read something like this in English
One of the *_no attributes is required; I don't care which one.
How do I go about that in yii2?
A bit of a hack but you can use the required validator with conditional validation:
public function rules() {
$oneOfUs = ['desk_no', 'mobl_no', 'faxx_no'];
return [
... //Your other rules here
[$oneOfUs, 'required', 'when' => function($model, $attribute) use ($oneOfUs) {
foreach (array_diff($oneOfUs, [$attribute]) as $f) {
return !!($model->$f);
}
return false;
}]
];
}
The above code works since the condition function will return true if any attribute except the current one is set. This will in turn run therequired validator on the current attribute.
you could use such validation for example
['desk_no', 'required', 'when' => function($model) {
return is_null($model->mobl_no)&&is_null($model->faxx_no);
}, message => "One of the *_no attributes is required; I don't care which one." ],
but if this logic can change, i prefer custom validator
Related
For validating form validation rules I currently stored them in User Model and use it in Register Controller, User controller in admin panel, User Controller in APIs and some other places, but currently it's very hard to maintain because each controller needs a slightly different set of rules and when I change the rules in User Model other controllers will not work anymore. So how to avoid duplication in rules and still keep the code maintainable?
Approach I often use is to write a HasRules trait for my models, it looks something like this:
trait HasRules
{
public static function getValidationRules(): array
{
if (! property_exists(static::class, 'rules')) {
return [];
}
if (func_num_args() === 0) {
return static::$rules;
}
if (func_num_args() === 1 && is_string(func_get_arg(0))) {
return array_get(static::$rules, func_get_arg(0), []);
}
$attributes = func_num_args() === 1 && is_array(func_get_arg(0))
? func_get_arg(0)
: func_get_args();
return array_only(static::$rules, $attributes);
}
}
Looks messy, but what it does is allows you to retrieve your rules (from a static field if such exists) in a variety of ways. So in your model you can:
class User extends Model
{
use HasRules;
public static $rules = [
'name' => ['required'],
'age' => ['min:16']
];
...
}
Then in your validation (for example, in your FormRequest's rules() method or in your controllers when preparing rules array) you can call this getValidationRules() in variety of ways:
$allRules = User::getValidationRules(); // if called with no parameters all rules will be returned.
$onlySomeRules = [
'controller_specific_field' => ['required'],
'name' => User::getValidationRules('name'); // if called with one string parameter only rules for that attribute will be returned.
];
$multipleSomeRules = User::getValidationRules('name', 'age'); // will return array of rules for specified attributes.
// You can also call it with array as first parameter:
$multipleSomeRules2 = User::getValidationRules(['name', 'age']);
Don't be afraid to write some code for generating your custom controller specific rules. Use array_merge and other helpers, implement your own (for example, a helper that adds 'required' value to array if it's not there or removes it etc). I strongly encourage you to use FormRequest classes to encapsulate that logic though.
You can try using laravel's validation laravel documentation
it is really easy to use and maintain just follow these steps:
run artisan command: php artisan make:request StoreYourModelName
which will create a file in App/Http/Requests
in the authorize function set it to:
public function authorize()
{
return true;
}
then write your validation logic in the rules function:
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
Custom error messages add this below your rules function:
public function messages()
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
Lastly to use this in your controller just add it as a parameter in your function.
public function create(Request $request, StoreYourModelName $storeYourModelName)
{
//
}
and that's all you need to do this will validate on form submission if validation passes it will go to your controller, keep in mind your validation logic does not have to be like mine thought i would show you one way that it can be done..
I'm using Laravel rules and I want to make a validation which requires multiple attributes.
For example, I want a rule to check that the quantity requested doesn't exceed the available stock for the given product. So, something like
public function rule() {
return [
'quantity produyctId' => "checkQty"
}
I would prefer to solve it using rules but other methods are also acceptable.
You can create a custom validation from extending the validation.
In AppServiceProvider class
Validator::extend('quantity_validity', function ($attribute, $value, $parameters, $validator) {
$productId = $parameters[0];
$quantity = $value;
// you can do whatever with these,
// and finally return true or false according to your desire.
});
In Validation
public function rule() {
return [
'quantity' => "quantity_validity:{$productId}"
]
}
I'm trying to add custom validation logic for file uploads for my admin panel. Right now my file fields can return either Illuminate\Http\UploadedFile or string|null if the file is not uploaded or changed or whatever. What I'm doing is, I created a custom rule that looks like this:
'image' => [
'required',
'admin_file:mimes:jpeg;png,dimensions:min_width=800;min_height=600'
]
I then parse all the arguments I pass, and the thing is, I naturally want all of them applied only if my value is an instance of UploadedFile. I use the following code for my custom validation:
<?php
class AdminFileValidator
{
public function validate($attribute, $value, $parameters, Validator $validator)
{
$rules = implode(
"|",
array_map(function($item) {
return str_replace(";", ",", $item);
}, $parameters)
);
$validator->sometimes($attribute, $rules, function() use ($value) {
return $value instanceof UploadedFile;
});
return true;
}
}
The problem is with adding additional rules to an attribute via sometimes doesn't work that way. The added rules are not being processed by a validator.
Is there any way to validate these rules without revalidating the whole thing manually?
What I see is that your are using sometimes inside of a rule. From my perspective you need to take it out, even better without use a custom class.
Using Validator object:
$validator = Validator::make($data, [
'image' => 'required',
]);
$validator->sometimes('image', 'mimes:jpeg;png,dimensions:min_width=800', function($value) {
return $value instanceof UploadedFile;
});
If you are using a Request class you could override the function getValidatorInstance in order apply the conditional rules:
protected function getValidatorInstance(){
$validator = parent::getValidatorInstance();
$validator->sometimes('image', 'mimes:jpeg;png,dimensions:min_width=800', function($value) {
return $value instanceof UploadedFile;
});
return $validator;
}
I want to change scenario in view page by jQuery.
There is a checkbox in my form, I want inputbox be required in checked checkbox.
my rule:
public function rules() {
return [
.
.
.
['pass' , 'required', 'on'=> 'checked']
]
}
my view page:
<?=$form->field($model, 'check')->checkbox()?>
<?=$form->field($model, 'Pass')->textInput(['maxlength' => 20])?>
Try to set up your rule like this:
public function rules() {
$checkBoxID = Html::getInputId($this, 'check');
return [
/* other rules */
['pass' , 'required',
'when' => function($model) {
return $model->check;
},
'whenClient'=> "function(attribute, value){
return $('#{$checkBoxID}').prop('checked');
}",
'on' => 'checked'
],
];
}
Read about conditional validation and whenClient validator property. Also consider naming you scenario more informative, e.g. by its purpose, like 'on' => 'sign-up', or 'on' => 'login'. Scenario is useful when you need certain rules to apply in particular cases, but you need to specify this scenario explicitly. Either when you instantiate a model
$model = new MyModel();
$model->scenario = 'sign-up';
and passing it into a view, or before doing any validation after $model->load($data)
I am trying to write a rule that validates if attribute_a or attribute_b is set;
one of the following attributes must be set : licitatii_publice or licitatiile_atribuite
The following code does not work;
<?php
namespace common\models;
use yii\base\Model;
class AbonamentValidare extends Model {
public $licitatii_publice;
public $licitatiile_atribuite;
public $zone;
public $judete;
public $tari;
public static $targetAttribute = [];
public function rules() {
return [
[['zone'], 'required'],
[['licitatii_publice', 'licitatiile_atribuite', 'tari', 'judete'], 'safe'],
['licitatii_publice', 'validate_tip_licitatie', 'targetAttribute' => ['licitatii_publice', 'licitatiile_atribuite']],
];
}
function validate_tip_licitatie($attribute, $param) {
print_r($attribute);
$this->addError($attribute, 'eroarea');
}
public function attributeLabels() {
return array(
'licitatii_publice' => 'lp',
'licitatiile_atribite' => 'la',
'tari' => 'tari',
'judete' => 'judete',
'zone' => 'zone',
);
}
public function save() {
return false;
}
}
?>
Just wanted to update this answer for Yii2 case.
In Yii2 the validators have a skipOnEmpty attribute which is by default set to true. This implies custom validators will not be called if the field is empty, which might not be the required behavior, especially in this case where either of one attribute is mandatory. In order to fix this issue we need to set the skipOnEmpty to false as shown below.
[['licitatii_publice, licitatiile_atribuite'], 'validate_tip_licitatie', 'skipOnEmpty'=> false],
Well what I have done in a case like this is to create the validator like this:
................
return [
[['zone'], 'required'],
[['licitatii_publice', 'licitatiile_atribuite', 'tari', 'judete'], 'safe'],
[['licitatii_publice, licitatiile_atribuite'], 'validate_tip_licitatie'],
];
............
function validate_tip_licitatie($attribute, $param) {
if(!$this->licitatii_publice && $this->licitatiile_atribuite)
$this->addError($attribute, 'eroarea');
}
In this way you show both fields with an error.
However I have done this in Yii1, but from what I read Yii2 should be the same. The logic is the same.
If you want to show error only for 1 attribute you can always just use
return [
[['zone'], 'required'],
[['licitatii_publice', 'licitatiile_atribuite', 'tari', 'judete'], 'safe'],
[['licitatii_publice'], 'validate_tip_licitatie'],
];
What you are trying to do is more fancy :), I get that. If you really want to use targetAttribute you might have to do it like this
https://github.com/yiisoft/yii2/blob/master/framework/validators/ExistValidator.php
Just build your own validator class.
Well. After reading about the exist validator i believe that is exactly what you need. It has examples on how to use it.