简体   繁体   中英

Custom Validation in PHP Codeigniter - one of two fields required

My form has a cellphone and a phone field. I want the user to fill either one of the fields, or both, but not neither.

I've seen ways to do it in other languages, but could I have some advice on how to do it with Codeigniter?

You can do it as:

$this->form_validation->set_rules('phone', 'Your validation message.', 'callback__phone_check');

And make a function:

function _phone_check() {
   //check for phone and cellphone field.
  //make sure one field is not empty and return accordingly
}

Hope that helps

Just wanted to throw some quick code snippets your way. I wanted to accomplish this and this question was one of the first entries in google when I did my search. I took inspiration from the other answers and here's what I did which worked for me (YMMV):

$this->form_validation->set_message('contactVerify', 'Either Phone or Email is required');
...
$this->form_validation->set_rules('phone', 'Phone', 'trim|callback_contactVerify[email]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|callback_contactVerify[phone]|valid_email|xss_clean');
...
public function contactVerify($contact, $otherField) {
  return ($contact != '' || $this->input->post($otherField) != '');
}

Since this is a very simple validation function, I pre-set the error message so I don't have to set it inside validation function. I pass in the other field I want to check as the second argument via the square brackets.

Hope this is useful.

Just do a JS validation on client-side, and PHP validation on server-side (or use CI's form helper)... Anyway, PHP should look something like this:

if ($_POST['cellphone'] == '' OR $_POST['phone' == '') {
// do stuff like make an notification, alert, etc... and take users back to the form
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM