Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_unique for codeigniter form validation

Tags:

I'm trying to figure out how I can use the is_unique rule from the Codeigniter form validation library in the following situation.

I'm trying to submit a edit user form and have the rule:

$this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean|is_unique[users.user_name]'); 

What if other values in the form are being changed but this value stays the same. The form is going to see that this value already exists so how would I protect it from editing if this value isn't changed.

like image 253
Kevin Smith Avatar asked Dec 03 '12 21:12

Kevin Smith


People also ask

How to set form validation in CodeIgniter?

CodeIgniter lets you set as many validation rules as you need for a given field, cascading them in order, and it even lets you prep and pre-process the field data at the same time. To set validation rules you will use the set_rules() method: $this->form_validation->set_rules();

How to set error message in CodeIgniter?

In addition, it has an error logging class that permits error and debugging messages to be saved as text files. By default, CodeIgniter displays all PHP errors. You might wish to change this behavior once your development is complete. You'll find the error_reporting() function located at the top of your main index.

Is unique form validation?

Using your code as an example, the is_unique validation rule works by looking for a field called user_name in your users database table. If the field with the same value exists it validates as false.


2 Answers

Using your code as an example, the is_unique validation rule works by looking for a field called user_name in your users database table. If the field with the same value exists it validates as false.

To make sure it runs only when the user submits a new value, you could check the posted value $this->input->post('user_name') against the value you pulled from the database to populate your form with. If they are the same, don't validate is_unique;

if($this->input->post('user_name') != $original_value) {    $is_unique =  '|is_unique[users.user_name]' } else {    $is_unique =  '' }  $this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean'.$is_unique); 
like image 151
Jeemusu Avatar answered Oct 29 '22 14:10

Jeemusu


There's a better way to go around it, I think, still using CodeIgniters' validation library... Use edit_unique where you pass an extra parameter which is the id of the row you're editing.. See below.. I use it and works pretty fine for me.. hope it helps

$this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean|edit_unique[users.user_name.'.$id.']'); 
like image 40
Anthony Mutisya Avatar answered Oct 29 '22 13:10

Anthony Mutisya