我对选择验证规则有疑问。
我将验证规则粘贴在模型中
public $validate = array(
'sentence_fields'=> array(
'select_chapter' => array(
'field'=>'select_chapter',
'label'=>'Select chapter',
'rules'=>'required|integer'
),
'source_sentence' => array(
'field'=>'source_sentence',
'label'=>'Source',
'rules'=>'trim|required|max_length[500]'
),
'translated_sentence' => array(
'field'=>'translated_sentence',
'label'=>'Translation',
'rules'=>'trim|required|max_length[500]'
),
'translated_translation' => array(
'field'=>'translated_translation[]',
'label'=>'Select another translation',
'rules'=>'trim|max_length[500]'
)
)
);
然后在控制器中调用它
$validate = $this->sentence_model->validate['sentence_fields'];
$this->form_validation->set_rules($validate);
那是针对create方法的,但我有一个不需要select_chapter
规则集的更新方法。
是否有一种简单的方法来调用此规则集(sentence_fields),但为我的更新方法排除select_chapter
?
感谢。
答案 0 :(得分:1)
如果你想将select_chapter排除在我的更新方法之外。只需使用数组的unset()
方法就可以了。
$validate = $this->sentence_model->validate['sentence_fields'];
unset($validate['sentence_fields']['select_chapter ']);//unsets your array
$this->form_validation->set_rules($validate);
答案 1 :(得分:1)
由于上述方法有效,我建议将其作为一种功能,以提高可读性和易用性。为此,请查看以下内容
public $validate = array(
'sentence_fields'=> array(
'select_chapter' => array(
'field'=>'select_chapter',
'label'=>'Select chapter',
'rules'=>'required|integer'
),
'source_sentence' => array(
'field'=>'source_sentence',
'label'=>'Source',
'rules'=>'trim|required|max_length[500]'
),
'translated_sentence' => array(
'field'=>'translated_sentence',
'label'=>'Translation',
'rules'=>'trim|required|max_length[500]'
),
'translated_translation' => array(
'field'=>'translated_translation[]',
'label'=>'Select another translation',
'rules'=>'trim|max_length[500]'
)
)
);
public function formValidationRules($validation, $unset = array()) {
if($unset) {
return $this->unsetValidation($unset);
} else {
return $this->validate[$validation];
}
}
private function ($unset) {
$validations = $this->validate[$validation];
foreach($unset as $key)
{
unset($validations[$key]);
}
return $validations;
}
这样您可以按照以下方式进行验证:
$validate = $this->sentence_model->formValidationRules('sentence_fields', ['select_chapter']);
$this->form_validation->set_rules($validate);