Welcome Guest, Not a member yet? Register   Sign In
Custom validation error messages.
#11

[eluser]skycrap[/eluser]
hmm,just joining,and found this thread is interesting.
using code above,and thanks it works,but i think it would be great if we can improve it so we can set custom error message based on fields and rules.
in other words we can set custom messages for every rule in every field (field can have more than one rule).
any idea?
#12

[eluser]Colin Williams[/eluser]
[quote author="skycrap" date="1216821227"]in other words we can set custom messages for every rule in every field (field can have more than one rule).
any idea?[/quote]

I think I catch what you're saying. CI already throws errors based on rules, and allows you to set custom messages per rule. However, it parses the rules in the order you provide, and stops at the first failure for input to satisfy a rule. And, that's the error you get.

To get what you're talking about, where a rule 'required|alpha|min_length[10]' could possibly display 3 errors, it would likely require overriding the _run() method, which is a bit of a hairy chunk of code to mess with. You would instead compound errors and set a flag that an error has occurred, then check that flag before breaking the loop.

If you're talking about setting custom rules per-field-per-rule, that is also certainly possible, but again, you'd be overriding _run(), in which case, you might as well work my custom method above into run, and not do the str_replace() function, which is a bit hackish.

So yeah, all very possible. But I don't think I'll tackle it until a project really requires it.
#13

[eluser]skycrap[/eluser]
wow,what a response,just a few minutes ago i posted.
yeah,i've think about that,it could be something to do with _run(),but yeah not this time i think Big Grin

thanks anyway Smile
#14

[eluser]Colin Williams[/eluser]
[quote author="skycrap" date="1216822803"]wow,what a response,just a few minutes ago i posted.[/quote]

Yeah, it's 4:40 AM where I'm at. I'm wired!
#15

[eluser]Colin Williams[/eluser]
Wiki'd now: http://codeigniter.com/wiki/Custom_Valid...per_Field/
#16

[eluser]danspam[/eluser]
The code given is not compatible with the new form validation library in CI 1.7. Here is a version that works with it, it's much simpler too:

Code:
function set_errors($fields) {
      if (is_array($fields) and count($fields))
      {
         foreach($fields as $key => $val)
         {
            if (isset($this->_field_data[$key]['error']) and $this->_field_data[$key]['error'] != '')
            {
                $new_error = sprintf($val, $this->_field_data[$key]['label']);        
                $this->_error_array[$key] = $new_error;
                $this->_field_data[$key]['error'] = $new_error;
            }
         }
      }    
   }




Theme © iAndrew 2016 - Forum software by © MyBB