Zend Framework notEmpty validator setRequired

好久不见. 提交于 2020-01-14 10:47:05

问题


I have looked at other questions/Googled this. My problem is that when I submit my form with empty textboxes that have a notEmpty validator, it triggers no error.

First, I would like to see if I understand the difference between notEmpty and setRequired. As I understand, the notEmpty validator gives an error if an element is submitted and the value is empty. That is, if an entry does not exist in the POST data (for forms), then it does not generate an error if the element is not required. Like it only runs if the element is set. The setRequired method will automatically add a notEmpty validator behind the scenes unless told otherwise. This ensures that an entry for an element must exist and it must not be empty. Correct?

Now, I tried to use this logic in my form where I added notEmpty validators, like so:

$username = new Zend_Form_Element_Text('txtUsername');
$username->addValidator(new Zend_Validate_NotEmpty(), true);

And the same for other text fields. If I submit my form without entering a value, my POST data looks like this:

(
    [txtUsername] => 
    [txtPassword] => 
    [txtRepeatPassword] => 
)

However, isValid still evaluates to true and no error messages are generated. Why? Shouldn't the notEmpty validator determine that the values are empty since the element has an entry in the POST data? If I use setRequired(true), it works how I want. It just messes with my mind that it determines that the username is not empty when the value is an empty string. :-)

Thanks in advance.


回答1:


I agree that this is a little confusing. The reason is that all form elements have an allowEmpty flag (true by default), that skips validation if the value is blank. It works this way because otherwise, adding validators to optional elements would be a real pain, e.g.:

$dateOfBirth = new Zend_Form_Element_Text('dob');
$dateOfBirth->setLabel('Date of birth (optional)');
$dateOfBirth->addValidator(new Zend_Validate_Date());
$form->addElement($dateOfBirth);

this would always fail validation if the user chose not to enter their DOB, as '' is not a valid date. With the allowEmpty flag on by default it works as you would expect (it only validates the date when one has been entered).

Calling setRequired(true) adds a NotEmpty validator but it also sets the allowEmpty flag to false. I would recommend you stick with this approach. Alternatively you can get your way to work by setting the flag as well:

$username = new Zend_Form_Element_Text('txtUsername');
$username->addValidator(new Zend_Validate_NotEmpty());
$username->setAllowEmpty(false);


来源:https://stackoverflow.com/questions/11701072/zend-framework-notempty-validator-setrequired

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!