Welcome Guest, Not a member yet? Register   Sign In
Messages for custom validations?
#1

[eluser]fireproofsocks[/eluser]
This seems like it's a long standing issue... (see http://ellislab.com/forums/viewthread/44627/ ) I've written some custom validation functions, e.g.

Code:
class MY_Form_validation extends CI_Form_validation {
//...
    function is_alpha_dash_extended($str)
    {
        if ( preg_match("/[^0-9a-zA-Z\.,!#\/\(\)\s\-_\[\]']/", $str) )
        {
            $this->CI->form_validation->set_message('is_alpha_dash_extended', 'Input contained invalid characters.');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

But the problem is that if multiple fields reference this function, they ONLY get the generic message. You can no longer tell which field used that message. E.g. if my form has 10 fields that used this rule, and 5 of the inputs were invalid, the user would see 'Input contained invalid characters.' five times and they'd have to guess which fields were invalid.

Is there a way to get the field name in the error message?
#2

[eluser]fireproofsocks[/eluser]
Well, I'm answering my own question... this is low-brow, but it works:

In my config file where I'm defining my form validation rules, I just tied into the simple parser:

Code:
//...
    'myform'    => array(
        array(
            'field' => 'firstName',
            'label' => 'First Name',
            'rules' => 'my_custom_validation_rule[First Name]'
        ),
//...

And then I updated my validation rules to accept an optional 2nd value:

Code:
function my_custom_validation_rule($str, $fieldname='Input')
    {
        if ( preg_match("/[^0-9a-zA-Z\.,!#\/\(\)\s\-_\[\]']/", $str) )
        {
            $this->CI->form_validation->set_message('my_custom_validation_rule'
                        , $fieldname.' contained invalid characters.');
            return FALSE; }
        else
        {
            return TRUE;
        }
    }
#3

[eluser]tomcode[/eluser]
If I remember right, one just has to create an entry in a language file with :
Code:
$lang['my_custom_validation_rule'] = "The %s field contains invalid characters.";

the validation method :
Code:
function my_custom_validation_rule($str)
{
       if ( preg_match("/[^0-9a-zA-Z\.,!#\/\(\)\s\-_\[\]']/", $str) )
       {
          return FALSE;
       }
       else
       {
            return TRUE;
       }
}

This should also work with set_message() method of the form_validation class. (Edit : if You don't use language files)




Theme © iAndrew 2016 - Forum software by © MyBB