Welcome Guest, Not a member yet? Register   Sign In
Form Validation set_message()
#1

[eluser]Peanut[/eluser]
Ok it's pulling the value correctly, but I guess I am not setting the message correctly. I know there is no rule called username_match.. or anything like that, but how do I display the error message with all the other validation errors? I just want to spit out a message if preg_match comes up false.

I have this:

Code:
$username = $this->input->post('username');
        if( ! preg_match('/(A-Za-z0-9)+/', $username)) {
            $this->form_validation->set_message('username_match', 'The %s field must only contain alpha-characters or numbers!');
        }

I basically just need another option instead of set_message() I guess.

Thanks for any help!
#2

[eluser]CroNiX[/eluser]
Are you creating a validation callback function or something?
#3

[eluser]Peanut[/eluser]
What would I do a callback for? Or wait.. that could actually work. But no, I'm creating a model and doing all the form_validation->set_rule blah blah blah there. It's validating everything for me since I'm interacting with the database and such as well.
So I'm just curious on how to set an error message. Like a totally custom default one that doesn't rely on any of the form_validation rule functions. Just a plain error message that will group itself with the other validation rules..
Basically throwing an exception. Will those be handled inside of the errors as well?
#4

[eluser]CroNiX[/eluser]
Well, that's not how the validation class was designed to be used. The only way to set custom error messages is to either override the global messages, or to create your own validation rules by either extending the form validation library or using validation callbacks (which can only be in a controller using stock CI).

The only way to set error messages is by the validation rule name, which is why the above will work.

for instance, you could create:
/application/libraries/MY_Form_validation.php

Code:
class MY_Form_validation extends CI_Form_validation {

  function __construct($config = array())
  {
    parent::__construct($config);
  }

  function username_match($str)  //str is the value from the form field this rule was used on
  {  
    if( ! preg_match('/(A-Za-z0-9)+/', $str))
    {
      //error message must be same as function name
      $this->set_message('username_match', 'The %s field must only contain alpha-characters or numbers!');
      return FALSE;  //failed
    }
    return TRUE;  //passed
  }
}

then in your controller
Code:
$this->load->library('form_validation');  //load validation, it will autoload your MY_Form_validation
$this->form_validation->set_rules('your-username-field', 'Username', 'required|username_match); //set the new rule to this field
If there is an error on 'your-username-field', it will output the error "The Username field must only contain alpha-characters or numbers!"




Theme © iAndrew 2016 - Forum software by © MyBB