Welcome Guest, Not a member yet? Register   Sign In
validation on a checkbox
#1

[eluser]stef25[/eluser]
when validating a checkbox with name='check', what rule should i use to make it gets checked? 'required' doesnt seem to work and the form passes validation even when its not checked.

anyone?
#2

[eluser]steelaz[/eluser]
I was searching forums about this today. There are a lot of good extensions to validation class, but if all you need is to make sure that checkbox (or at least one checkbox in array) is checked, you have to add two rules:

Code:
$rules['chkArray'] = 'required|isset';

"isset" rule is undocumented, not sure why.

I hope someone will find this useful.
#3

[eluser]nate_02631[/eluser]
[quote author="steelaz" date="1206316814"]"isset" rule is undocumented, not sure why.[/quote]
Hi - actually it's not undocumented. The validation docs states that *any* PHP function that accepts a single parameter can be used in validation rules, i.e. "is_numeric", etc...
#4

[eluser]steelaz[/eluser]
That true, but validation class is treating "isset" separately. This comment is from Validation.php :
Code:
/*
* Are we dealing with an "isset" rule?
*
* Before going further, we'll see if one of the rules
* is to check whether the item is set (typically this
* applies only to checkboxes).  If so, we'll
* test for it here since there's not reason to go
* further
*/
#5

[eluser]maesk[/eluser]
@steelaz, thank you, I found this very useful indeed! After spending some hours trying to make validation of a checkbox work and setting a custom error message for the checkbox I found this post and it finally works now! Here's my code (snippet)

Code:
// Set Rules for required fields
    $rules['sender_name'] = "required";
    $rules['from'] = "required|valid_email";
    $rules['to'] = "required|valid_email";
    $rules['terms'] = "required|isset";
    $this->validation->set_rules($rules);

...

// Set multilingual custom error messages
    $this->validation->set_message('required', $this->lang->line('Required'));
    $this->validation->set_message('valid_email', $this->lang->line('ValidEmail'));
    $this->validation->set_message('isset', $this->lang->line('PleaseAcceptTerms'));




Theme © iAndrew 2016 - Forum software by © MyBB