Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

php - Creating a custom codeigniter validation rule

I have a function in my login form that checks if the email and password match the values in the database and if so it logs the user into the system.

I would like to display a validation error if this function returns false.

My problem is that I am unsure how to go about creating this. The message relates to both the password and email fields so I would not want a rule for each input field just display a single message.

I have tried using flashdata to achieve this but it only works when the page has been refreshed.

How can I created a new validation rule solely for the function $this->members_model->validate_member() ??

$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        $this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', '"Password"', 'trim|required');

        if ($this->form_validation->run() == FALSE)
        {
            $viewdata['main_content'] = 'members/login';
            $this->load->view('includes/template', $viewdata);
        }
        else
        {       
                if($this->members_model->validate_member())
                {
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You use the callback_ in your rules, see callbacks, for ex.

$this->form_validation->set_rules('email_address', '"Email address"', 'trim|required|valid_email|callback_validate_member');

and add the method in the controller. This method needs to return either TRUE or FALSE

function validate_member($str)
{
   $field_value = $str; //this is redundant, but it's to show you how
   //the content of the fields gets automatically passed to the method

   if($this->members_model->validate_member($field_value))
   {
     return TRUE;
   }
   else
   {
     return FALSE;
   }
}

You then need to create a corresponding error in case the validation fails

$this->form_validation->set_message('validate_member','Member is not valid!');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...