Question

In a model User I have this field.

 $this->addField('login')->mandatory(true)->caption('Login')->length(10);

But when I enter text longer than 10 characters, the validation never occurs, and never shows the red message below the field saying: "text too long"

How can I do this in agile toolkit 4.2.4?? I miss something basic???

Thanks in advice!!

Was it helpful?

Solution

As said in Field class length() method description:

 This will provide a HTML settings on a field for maximum field size.
 The length of a field will not be enforced by this setting.
 ...

Field->length($n) doesn't do any validation itself. It's just there for form field display purposes and also you can use this value somewhere in your own validation class something like this:

// In model class file init method
$model->addHook('beforeSave', array($this, 'customValidation'));

// In model class file
function customValidation() {
    foreach ($this->getActualFields() as $f) {
        $field = $this->getField($f);
        if ($field->length && strlen($this[$f]) > $field->length) {
            throw $this->exception('Field value to long', 'Exception_ValidityCheck')
                ->addMoreInfo('field', $f)
                ->addMoreInfo('value', $this[$f])
                ->addMoreInfo('limit', $field->length);
        }
    }
}

Code above is completely untested - just to give you idea. You can also validate field value length on Form submit hook, but that's not exactly correct. Better is to do this in Model.

Also check out validation add-on made by Romans https://github.com/romaninsh/validation. It's has to be very powerful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top