Form Validation: One set of rules for all forms of same model - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12) +--- Thread: Form Validation: One set of rules for all forms of same model (/showthread.php?tid=63893) |
Form Validation: One set of rules for all forms of same model - gastongr - 12-19-2015 Hello everyone, I am using the CI form validation library in my controllers but i have the validation rules defined in the models. For example in my Users controller, in the edit() method i have: PHP Code: // Get the rules from the model Then in the same controller the other methods use different validation rules, for example user_login_rules, user_create_rules and so. This results in many sets of rules for the same fields. The thing is that i want a single set of validation rules that represent the restrinctions of the whole model. For example: PHP Code: public $user_rules = array( But when i use this rules, for example, for the login page the validation fails because some data is not submitted in the login form. So i want the validation library to only take into account the fields that have been submitted. I think this would be possible since submitting an empty field means it will exist in $_POST[] as an empty string which is different from not submitting it. Any advice on how to accomplish this? maybe implementing a MY_Form_validation.php but i am not sure. Thanks so much RE: Form Validation: One set of rules for all forms of same model - jaynarayan - 12-20-2015 use unset function before passing the array to set rule methode. For example if yo dont want to validate password confirm in login page, // Get the rules from the model $rules = $this->user_model->user_edit_rules; Unset($rules[password]); // Set the rules $this->form_validation->set_rules($rules); RE: Form Validation: One set of rules for all forms of same model - gastongr - 12-20-2015 Great thanks! Your idea made me think i could do it like this: PHP Code: $login_rules = elements(array('username', 'password'), $this->user_model->all_rules); Thanks again for taking the time to answer! RE: Form Validation: One set of rules for all forms of same model - skunkbad - 12-20-2015 You might want to consider extending the Form validation class with a MY_Form_validation.php and putting the following method in it: PHP Code: /** This allows you to put commonly used form validation rules in a model or library. See the comments. PS. This is included in Community Auth RE: Form Validation: One set of rules for all forms of same model - gastongr - 12-20-2015 Thanks for the suggestion @skunkbad ! |