Codeigniter: checking two fields

I have two numeric fields for collecting data from users. You must verify it using the code form validation class.

Terms:

  • The first field may be zero
  • The second field cannot be zero
  • The first field should not be equal to the second field
  • The second field must be larger than the first field

I am currently using

$ this-> form_validation-> set_rules ('first_field', 'First Field', 'Trim | required | is_natural');

$ this-> form_validation-> set_rules ('second_field', 'Second Field', 'Trim | required | is_natural_no_zero');

But, how to approve for the 3rd and 4th conditions mentioned above?

Thanks in advance.

+4
source share
3 answers

Thanks dm03514. I got it working using the callback function below.

$this->form_validation->set_rules('first_field', 'First Field', 'trim|required|is_natural'); $this->form_validation->set_rules('second_field', 'Second Field', 'trim|required|is_natural_no_zero|callback_check_equal_less['.$this->input->post('first_field').']'); 

and callback function:

 function check_equal_less($second_field,$first_field) { if ($second_field <= $first_field) { $this->form_validation->set_message('check_equal_less', 'The First &amp;/or Second fields have errors.'); return false; } else { return true; } } 

Now everything works fine :)

+16
source

You can write your own validation function for 3 and 4 using callbacks

http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#callbacks

Example from the document

 <?php class Form extends CI_Controller { public function index() { $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->form_validation->set_rules('username', 'Username', 'callback_username_check'); $this->form_validation->set_rules('password', 'Password', 'required'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); $this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]'); if ($this->form_validation->run() == FALSE) { $this->load->view('myform'); } else { $this->load->view('formsuccess'); } } public function username_check($str) { if ($str == 'test') { $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"'); return FALSE; } else { return TRUE; } } } ?> 
+4
source

If you use HMVC and the decision does not work, add the following line after initialization in the controller

 $this->form_validation->CI =& $this; 

So it will be

 $this->load->library('form_validation'); $this->form_validation->CI =& $this; 

in your controller.

0
source

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


All Articles