Apply same validation rule for multiple fields

2019-06-25 09:05发布

问题:

How do i apply same validation rule for 50 fields in 2.0

i am not interested in repeating rule for different field

public $validate = array(
    'company' => array(
        'notempty' => array(
            'rule' => array('notempty'),
            'message' => 'Cannot be Empty',

        ),
    ),
    // rule for other 50 fields....
);

回答1:

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

Don't understand why you want to determinate same validation 50 times. You can declare just one rule and use it for all your fields.

May be I misunderstood your question?



回答2:

You can dynamically build your $validate rules before you perform the save in your 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 the fields you want to apply the validation to.

Idealy, You'd shift the code that builds the validation array to the model, but the effect is the same

You can apply the same technique to allow you to have multiple validation rules for a model.



回答3:

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