编程语言
首页 > 编程语言> > php – 如何自定义Zend_Form正则表达式错误消息?

php – 如何自定义Zend_Form正则表达式错误消息?

作者:互联网

我有以下代码:

    $postcode = $form->createElement('text', 'postcode');
    $postcode->setLabel('Post code:');
    $postcode->addValidator('regex', false, 
        array('/^[a-z]{1,3}[0-9]{1,3} ?[0-9]{1,3}[a-z]{1,3}$/i'));
    $postcode->addFilters(array('StringToUpper'));
    $postcode->setRequired(true);

它在表单中创建一个输入字段并设置正则表达式验证规则并且工作得很好.

问题是当用户输入无效的邮政编码时显示的错误信息是:

'POSTCODE' does not match against pattern
    '/^[a-z]{1,3}[0-9]{1,3} ?[0-9]{1,3}[a-z]{1,3}$/i'

(输入是POSTCODE)

如何更改此消息以使其更友好?

解决方法:

我想要记住,您可以在Validator中设置错误消息:

$postcode = $form->createElement('text', 'postcode');
$postcode->setLabel('Post code:');
$postcode->addValidator('regex', false, array(
    'pattern' => '/^[a-z]{1,3}[0-9]{1,3} ?[0-9]{1,3}[a-z]{1,3}$/i')
    'messages' => array(
        'regexInvalid'   => "Invalid type given, value should be string, integer or float",
        'regexNotMatch' => "'%value%' does not match against pattern '%pattern%'",
        'regexErrorous'  => "There was an internal error while using the pattern '%pattern%'"
    )
);
$postcode->addFilters(array('StringToUpper'));
$postcode->setRequired(true);

如果这不起作用,请尝试

> setErrorMessages(array $messages):添加多个错误消息以显示表单验证错误,覆盖所有先前设置的错误消息.

标签:php,regex,html-form,zend-framework,zend-form
来源: https://codeday.me/bug/20190607/1191199.html