How to create dependency validation between fields in Codeigniter?

Asked

Viewed 1,098 times

0

In Codeigniter there is the possibility to create rules (Rules) validation for each form field, but what I need is a validation between two fields. I explain:

The form has a field called url which is only obligatory if the flag correspondent is selected.

  • I do not know if in Codeigniter you can do this, because it is a validation on the Client’s side (possibly even gives). If you cannot try javascript/jquery

  • With javascript is easier to do and is proto even, but it is good to have a validation in the backend as well.

  • As @Luiscoms commented, I also believe that the ideal is to have validation on both sides. In client-side you can prevent a form from being submitted with errors, avoiding unnecessary processing on the server-side; and on the server-side, to prevent a possible bug in client-side validation from being exploited.

2 answers

2


It is possible, but you will have to use the callback_XXX validators:

public function index(){
  $this->form_validation->set_rules('flag', 'Flag', '');
  $this->form_validation->set_rules('url', 'URL', 'callback_checaflag');
}

public function checaflag($url){
    if($this->input->post('flag')){
      return $this->form_validation->required('url');
    }
}
  • Thanks for the reply @Neto just added a validation code that I found in Valid-url-format-checking-in-codeignite: 
 public function checaflag($url) {
 $pattern = "/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
 if($this->input->post('flag')){
 return (bool)preg_match($pattern, $url);//$this->form_validation->required('url');
 }
 }


  • It’s really a shame the CI doesn’t have a Rule to validate URL

0

Another alternative @Luiscoms, would be to do something like:

public function index(){
    // Se tal campo estiver marcado, adicionar a regra para validar a URL
    if($this->input->post('eu_aceito')){
         $this->form_validation->set_rules('url', 'URL', 'callback_validaurl');
    }
}

public function validaurl($url){
    // Colocar aqui funcao para vallidar $url e retornar TRUE ou FALSE
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.