phpcodeignitervalidation

CodeIgniter's form_validation rule is not showing message for valid or invalid input


I don't know what's not working. I know my form validation is definitely working because all my other functions work properly.

I am setting messages whether it's true OR false and neither of them show up so I feel like it's skipping right over the validation rule.

$this->form_validation->set_rules('region', 'required|valid_region');

The rule in MY_Form_validation.php in my libraries folder. The library IS loaded first. As I said, all my other validations work properly such as my reCaptcha and everything.

function valid_region($str) {
    $this->load->database();
    if ($this->db->query(
            'SELECT id FROM region WHERE name = ? LIMIT 1',
            array($str)
        )->num_rows() == 0
    ) {
        //not a valid region name
        $this->set_message(
            'valid_region',
            'The %s field does not have a valid value!'
        );
        return false;
    }
        
    $this->set_message('valid_region', 'Why is it validating?');
}

None of the messages will set so I have a feeling nothing is validating!


Solution

  • set_rules() function takes 3 parameters

    1. The field name - the exact name you've given the form field.
    2. A "human" name for this field, which will be inserted into the error message. For example, if your field is named "user" you might give it a human name of "Username". Note: If you would like the field name to be stored in a language file, please see Translating Field Names.
    3. The validation rules for this form field.

    You put the validation rules as second parameter. That is why the validation is not running. Try this instead:

    $this->form_validation->set_rules('region', 'Region', 'required|valid_region');