Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

zend framework - Laminas / ZF3: Add manually Error to a field

is it possible to add manually an Error Message to a Field after Field Validation and Input Filter ?

I would need it in case the Username and Password is wrong, to mark these Fields / Display the Error Messages.

obviously in ZF/ZF2 it was possible with $form->getElement('password')->addErrorMessage('The Entered Password is not Correct'); - but this doesnt work anymore in ZF3/Laminas

question from:https://stackoverflow.com/questions/65921881/laminas-zf3-add-manually-error-to-a-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Without knowing how you do your validation (there are a few methods, actually), the cleanest solution is to set the error message while creating the inputFilter (and not to set it to the element after it has been added to the form).

Keep in mind that form configuration (elements, hydrators, filters, validators, messages) should be set on form creation and not in its usage.

Here the form is extended (with its inputfilter), as shown in the documentation:

use LaminasFormForm;
use LaminasFormElement;
use LaminasInputFilterInputFilterProviderInterface;
use LaminasValidatorNotEmpty;

class Password extends Form implements InputFilterProviderInterface {

    public function __construct($name = null, $options = []) {
        parent::__construct($name, $options);
    }

    public function init() {
        parent::init();

        $this->add([
            'name' => 'password',
            'type' => ElementPassword::class,
            'options' => [
                'label' => 'Password',
            ]
        ]);
    }

    public function getInputFilterSpecification() {
        $inputFilter[] = [
            'name' => 'password',
            'required' => true,
            'validators' => [
                [
                    'name' => NotEmpty::class,
                    'options' => [
                        // Here you define your custom messages
                        'messages' => [
                            // You must specify which validator error messageyou are overriding
                            NotEmpty::IS_EMPTY => 'Hey, you forgot to type your password!'
                        ]
                    ]
                ]
            ]
        ];
        return $inputFilter;
    }
}

There are other way to create the form, but the solution is the same.
I also suggest you to take a look at the laminas-validator's documentation, you'll find a lot of useful informations


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...