Apply one validation rule for multiple fields

How to apply one validation rule for 50 fields in 2.0

I am not interested in repeating a rule for another field

public $validate = array( 'company' => array( 'notempty' => array( 'rule' => array('notempty'), 'message' => 'Cannot be Empty', ), ), // rule for other 50 fields.... ); 
+4
source share
3 answers

Possible Solution:

 $validate_items = array('company', 'other', 'one_more'); $validate_rule = array( 'notempty' => array( 'rule' => array('notempty'), 'message' => 'Cannot be Empty') ); $validate = array(); foreach ($validate_items as $validate_item) { $validate[$validate_item] = $validate_rule; } echo "<pre>".print_r($validate, true)."</pre>"; 

I don’t understand why you want to define the same check 50 times. You can declare only one rule and use it for all of your fields.

Perhaps I misunderstood your question?

+2
source

You can dynamically create your own $ validate rules before saving to the controller:

public function add () {

 if (!empty($this->request->data) { $validate = array(); foreach($fields as $field) { $validate[$field] = array( 'required'=>array( 'rule'='notEmpty', 'message'=>'Cannot be empty' ) ); } $this->ModelName->validate = $validate; if (!$this->ModelName->save($this->request->data)) { // didn't save } else { // did save } } 

}

Where $ fields is an array containing a list of fields to which you want to apply validation.

Idealy, you would move the code that builds the validation array in the model, but the effect is the same

You can use the same method to allow you to have multiple validation rules for the model.

+1
source

New example:

 $fields_to_check = array('company', 'field_2', 'field_5'); // declare here all the fields you want to check on "not empty" $errors = 0; foreach ($_POST as $key => $value) { if (in_array($key, $fields_to_check)) { if ($value == "") $errors++; } } if ($errors > 0) echo "There are ".$errors." errors in the form. Chech if all requered fields are filled in!"; //error! Not all fields are set correctly else //do some action 
0
source

Source: https://habr.com/ru/post/1387181/


All Articles