Php – How to customise Zend_Form regex error messages

formsPHPregexzend-formzend-framework

I have the following code:

    $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);

It creates an input field in a form and sets a regex validation rule and works just fine.

The problem is that the error message it displays when a user enters an invalid postcode is this:

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

(where input was POSTCODE)

How can I change this message to be a little more friendly?

Best Answer

I think to remember, you can set the error message in the 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);

If that doesn't work, try

  • setErrorMessages(array $messages): add multiple error messages to display on form validation errors, overwriting all previously set error messages.