Custom meaningful error message for Zend RegEx Validator

I check the text box in my form as follows:

$name = new Zend_Form_Element_Text('name'); $name->setLabel('First Name:') ->setRequired(true) ->addFilter(new Zend_Filter_StringTrim()) ->addValidator('regex',true,array('/^[(a-zA-Z0-9)]+$/')) ->addErrorMessage('Please enter a valid first name'); 

What I'm trying to accomplish is how can I display a meaningful error message? For example: if the name is โ€œXYZ-โ€, how can I display โ€œ- not allowed by nameโ€.

Is there a way by which I can access which character the regular expression fails to execute? Would you recommend anything else?

I was thinking of writing a custom validator, but the regex is pretty simple, so I don't see the point. I could not find decent documentation for the zend 'regex' validator anywhere.

If I do not override the default error message, I just get something like: ';;; hhbhbhb 'does not match the pattern' / ^ [(a-zA-Z0-9)] + $ / '- which I obviously do not want to show to the user.

I would be grateful for your materials.

+6
php regex zend-framework zend-form
source share
2 answers

How to tell the user on non-professional terms, what are your limitations? how

 Error: Only the letters A to Z and numbers are allowed. 

(which leads me to the question of why the first names may contain numbers ...)

+1
source share

For your custom error messages in standard zend validators, just pass the messages array to the validator when creating the instance. This is an array whose keys are types of errors (see below), and the values โ€‹โ€‹are error messages.

 ->addValidator('regex', true, array( 'pattern'=>'/^[(a-zA-Z0-9)]+$/', 'messages'=>array( 'regexNotMatch'=>'Your own custom error message' ) ) ) 

To see error keys for other types of errors of the selected validator, you can refer to its source code. For the regex validator, it is located in {Zend Framework Library} /Zend/Validate/Regex.php.

Good luck checking :).

+15
source share

All Articles