Roman
Roman

Reputation: 3749

Codeigniter form validation

Can I display a single message for the multiple form fields in CodeIgniter? For example, I have set following rules for the email and password fields. I want to display only one message if any of these two fields is invalid. (eg. invalid email or password ")

$this->form_validation->set_rules('email_address', 'Email Address', 'valid_email|required');
$this->form_validation->set_rules('password', 'Password', 'required|min_length[4]');

How i can do that? Thanks for any help.

Edit: Sorry if my question is not clear. Currently I'm using validation_errors(), and i get errors of each field. However, I want to show a same error message if any of the two fields (email or password) is invalid. No matter if email is invalid, or if password is invalid, or both are invalid, it should print a single message, such as: invalid email or password.

Upvotes: 1

Views: 7253

Answers (4)

kirkaracha
kirkaracha

Reputation: 752

In your view you can just do this:

<?php if(!empty($this->form_validation->_error_array)): ?>
    <p>There were some errors.</p>
<?php endif; ?>

Upvotes: 1

Mitchell McKenna
Mitchell McKenna

Reputation: 2276

Iterate over each field and check using form_error(), add any invalid field names to a single error string:

if($this->form_validation->run() == FALSE){
   $fields = array('email_address', 'password');
   $invalid_fields = array(); //where we'll store invalid field names
   foreach($fields as $field){
      if(form_error($field)){
         $invalid_fields[] = $field;
      }
   }
   $data['error_message'] = 'The following fields are invalid: ' . implode(",", $invalid_fields);
}
$this->load->view('yourview', $data); //if !empty($error_message) in view echo it out

Upvotes: 3

Jorge Guberte
Jorge Guberte

Reputation: 11054

I'm not sure if this is what you need, but you can try:

if($this->form_validation->run() == FALSE){
   $message = 'Your error message here'; //validation_errors() works too.
}else{
   $message = 'Your success message here';
}

$this->load->view('yourview',array('feedback_message'=>$message));

If you don't care which field isn't valid, then this snippet is ok. "Something is wrong, i don't care what's wrong, tell the user".

Upvotes: 3

Vamsi Krishna B
Vamsi Krishna B

Reputation: 11490

$this->form_validation->set_message('rule', 'Error Message');

I think ,setting the same error message for both the rules will do the job ;)

Upvotes: 0

Related Questions