Help with field validation on a module
I am trying to understand how to use validations on my modules.
I have a simple module where the user need to capture a year.
I am trying to validate the year field to have minimum 4 characters.
Whatever I try, I get no error when the field is less than 4 characters.
Here is what I've tried:
1.
class Donation_Months_model extends Base_module_model
{
public $length_min = array('year','4');
2. class Donation_Months_model extends Base_module_model
{
public $length_min = array('year'=>'4');
3.
function on_before_save($values)
{
$this->add_validation('year', 'length_min', 'b', array($values['year'], '4'));
}
4.
function on_before_save($values)
{
$this->validatior->add_rule('year', 'length_min', 'b', array($values['year'], '4'));
}
Please, can someone help me here?
Comments
#3 - the data is just being saved to the database with no error.
#4 - I get this error:
Severity: Notice
Message: Undefined property: Module::$validatior
Filename: core/Model.php
Line Number: 50
Can you maybe also explain to me when do I use this when should I use add_validation, or validator or a public variable like $require?
function form_fields($values = array())
{
$fields = parent::form_fields();
$fields['year']['type'] = 'year';
$fields['year']['value'] = date('Y');
Tried to capture year 1, and the data was saved to the database.
For #4, it looks like it may be a typo... it should be $this->validator->add_rule(...).
With regards to usage, I would recommend using the add_validation method on the model which is essentially an alias to $this->validatior->add_rule(...), whenever there is additional validation you may need to make on a field. By default, fields will be auto-validated to make sure they are the right length (if length restrictions exist on the field as in varchar and int), or that dates are formatted correctly. In this case the year field type has this auto-validation already assigned to it. Also, I would use the $required property on the model for any field that needs to be set for the record to have validity.
Ok, changed the column in the database to year and everything is fine now.
Just one question, when you say: "fields will be auto-validated to make sure they are the right length (if length restrictions exist on the field as in varchar and int)" do you mean the field's length in the database?
Thank you very much.
I think to do it in the form fields you probably wanted a type = date. (at a guess..)