I'm having a form with an element username
. There are two validators: NotEmpty
and StringLength
. The custom error messages for StringLength
are working, but somehow it does not use the custom error message for the NotEmpty
validator. In ZF1 the notEmpty validator was added automatically when making an element required which could be turned off. I can't find such an option in ZF2 and maybe my NotEmpty validator is not used because it was already added by the required flag!?
我有一个元素用户名的表单。有两个验证器:NotEmpty和StringLength。StringLength的自定义错误消息正在工作,但不知何故,它不为NotEmpty验证器使用自定义错误消息。在ZF1中,当需要一个可以关闭的元素时,notEmpty验证器会自动添加。我在ZF2中找不到这样的选项,可能我的notEmpty验证器没有被使用,因为它已经被必需的标志添加了!?
$inputFilter->add($factory->createInput(array(
'name' => 'username',
'required' => true,
'filters' => array(
array(
'name' => 'StringTrim'
),
),
'validators' => array(
array(
'name' => 'NotEmpty',
'options' => array(
'messages' => array(
NotEmpty::IS_EMPTY => 'Bitte geben Sie Ihren Benutzernamen ein.',
),
),
),
array(
'name' => 'StringLength',
'options' => array(
'min' => 3,
'max' => 45,
'messages' => array(
StringLength::TOO_SHORT => 'Der Benutzername muss mindestens 3 Zeichene lang sein.',
StringLength::TOO_LONG => 'Der Benutzername darf maximal 45 Zeichen lang sein.',
)
),
),
),
)));
2 个解决方案
#1
5
The ZF2 Form, by default, adds validators for the different form elements automatically when creating them. To prevent the defaults from being added and only have your validators present, you need to add to the form constructor:
默认情况下,ZF2表单在创建不同的表单元素时自动添加验证器。为了防止添加的默认值,并且只有您的验证器存在,您需要添加到表单构造函数:
$this->setUseInputFilterDefaults(false);
$ this - > setUseInputFilterDefaults(假);
This will prevent the Form object from adding those default validators. Now when you add your own NotEmpty, or any other element for that matter, validator with a custom message, that message is used instead of the default one.
这将防止表单对象添加这些默认验证器。现在,当您添加自己的NotEmpty或任何其他元素(带有自定义消息的验证器)时,将使用该消息而不是默认消息。
#2
2
It was a bug in the version I was using. After updating to the latest revision on GitHub it works fine.
这是我使用的版本中的一个错误。在更新到GitHub的最新修订之后,它运行得很好。
#1
5
The ZF2 Form, by default, adds validators for the different form elements automatically when creating them. To prevent the defaults from being added and only have your validators present, you need to add to the form constructor:
默认情况下,ZF2表单在创建不同的表单元素时自动添加验证器。为了防止添加的默认值,并且只有您的验证器存在,您需要添加到表单构造函数:
$this->setUseInputFilterDefaults(false);
$ this - > setUseInputFilterDefaults(假);
This will prevent the Form object from adding those default validators. Now when you add your own NotEmpty, or any other element for that matter, validator with a custom message, that message is used instead of the default one.
这将防止表单对象添加这些默认验证器。现在,当您添加自己的NotEmpty或任何其他元素(带有自定义消息的验证器)时,将使用该消息而不是默认消息。
#2
2
It was a bug in the version I was using. After updating to the latest revision on GitHub it works fine.
这是我使用的版本中的一个错误。在更新到GitHub的最新修订之后,它运行得很好。