Zend Validate, Display one message per validator - zend-validate

I am validating an email address using zend_validate_email.
For example, for email address aa#aa it throws several error messages including very technical describing that DNS mismatch (:S).
I am trying to make it display only 1 message that I want it to (for example: "Please enter a valid email").
Is there any way of doing it elegantly, apart from creating a subclass and overriding the isValid method, clearing out the array of error messages?
Thanks!

$validator = new Zend_Validate_EmailAddress();
// sets the message for all error types
$validator->setMessage('Please enter a valid email');
// sets the message for the INVALID_SEGMENT error
$validator->setMessage('Something with the part after the # is wrong', Zend_Validate_EmailAddress::INVALID_SEGMENT);
For a full list of errors and message templates see the Zend_Validate_EmailAddress class

Related

Play - Custom validations with custom error message

I am using the Play framework in Scala to develop a small blog website. I currently have a form (successfully) set up for an easy registration of users. This login page just accepts a username (ie. no password yet), verifies that is of the appropriate length and doesn't exist yet, and adds this user to the database (currently still in memory). Length can be verified using just the basic form functionality, however, the uniqueness of this username required me to use custom validations.
Now, this all works, except for the custom error message. When a normal form requirement is not fulfilled, an error message is returned and displayed in the view (eg. "The minimum length is: 5"). I want to display a similar message when the name is not unique. In the first link I provided there is an example of custom validations which seems to have an argument that represents such custom error message for validations you write of your own. However, this does not display in the view, while the others do.
Current validation code:
private val myForm: Form[Account] =
Form(mapping("name" -> text(3, 24))(Account.apply)(Account.unapply).verifying(
"Account is not in the DB.",
fields =>
fields match {
case data: Account => accountExists(data.name).isDefined
}
)
)
Anyone has any ideas?

Altering a Drupal form after validation

I have a Drupal 7 form where after submitting it, some validation happens. It is taking the email address and doing a database look-up to see if that user already exists. If the user exists, I need to alter the form that re-renders on the page that normally displays the errors, removing some fields. Basically on the error page, regardless of any other validation errors they would have normally received (First name required, last name required etc.) they would only get one error message that says "that email address is already in the system" and then I no longer want to display ANY of the other fields at this point except the email address field and a file upload field. So I'm having trouble trying to figure out how to alter the form after the first submission based on some validation.
Thanks
What you want to do is add some data to the $form_state variable in your validation function that can inform your form function as to what fields it should provide.
Untested Example:
function my_form($form, &$form_state){
$form['my_field1'] = array('#markup' => 'my default field');
// look for custom form_state variable
if ($form_state['change_fields']) {
$form['my_field2'] = array('#markup' => 'my new field');
}
}
function my_form_validate($form, &$form_state){
// if not valid for some reason {
form_set_error('my_field1','this did not validate');
$form_state['change_fields'] = true;
// }
}

Editing Gateway Errors

How do you customize the Gateway Errors that pop up when a customer's credit card is declined.
Example would be "Payment transaction failed. Reason Gateway error: An error occurred during processing. Please try again."
We're using Authorize.net if that makes a difference. To clarify, we aren't looking to get rid of them, just modify the language in them.
Copy the file app/code/core/Mage/Paygate/Model/Authorizenet.php to local. Then find this (line 1334):
protected function _wrapGatewayError($text)
{
return Mage::helper('paygate')->__('Gateway error: %s', $text);
}
and replace with this:
protected function _wrapGatewayError($text)
{
if($text == 'This transaction has been declined.') {
$text = 'Custom message here.';
}
return Mage::helper('paygate')->__('Gateway error: %s', $text);
}
I know this is an old question, but I will leave this here for the future in case if someone runs into this.
The _wrapGatewayError() method already uses a helper to output the message, so why not just translate the message?
Create (or edit) your localization/translation file in app/design/frontend/{package_name}/{theme_name}/locale/en_US/translate.csv. You can check the active package_name and theme_name in System / Configuration / Design (under 'General').
Add the messages you are changing to that file in this format: "Old text - message you want to change", "New message".
In your case, it will be something like this:
"Payment transaction failed. Reason Gateway error: An error occurred during processing. Please try again.", "Your custom message"
How it works: whenever a helper is used to output the "Payment translation failed. ...", the system will find the translation file (translate.csv) and will change the message to your custom one.
Please don't modify core files. It creates a mess, interferes with patches, and makes debugging harder. You can extend them if you need to. See Overriding Magento blocks, models, helpers and controllers

Chaining Error Messages in Zend Framework

It seems that using addErrorMessage() overrides all other validation errors.
For example, I created a custom phone element. And I also created a custom validation class that checks for a custom business rule.
I expected it to print out the error messages from My_Validate_BusinessPhone when it did not meet the custom business rule. But it prints message set in addErrorMessage() all the time. Is this the normal behavior? Is there a way to chain the error messages?
$phone = new My_Form_Element_Phone( 'phone' );
$phone->setRequired( TRUE )
->setAttrib( 'id', 'phone' )
->addErrorMessage( 'Please provide a valid phone number' )
->addValidator( new My_Validate_BusinessPhone );
I thank you in advance.
The messages are overwritten, because you are setting the message to the form element and not to the validator. So that's how it should work: First, get your form element. In your case, just use it. Second, get the validator by name (I don't know how it's exacly called here, e.g. it could be 'notEmpty') and third, add your message for this validator.
$phone->getValidator('yourValidatorsName')->setMessage('Please provide a valid phone number');
I've just tested this in my own script, but I hope it should work ;-)

Zend_Validate_Abstract custom validator not displaying correct error messages

I have two text fields in a form that I need to make sure neither have empty values nor contain the same string.
The custom validator that I wrote extends Zend_Validate_Abstract and works correctly in that it passes back the correct error messages. In this case either: isEmpty or isMatch.
However, the documentation says to use addErrorMessages to define the correct error messages to be displayed.
in this case, i have attached
->addErrorMessages(array("isEmpty"=>"foo", "isMatch"=>"bar"));
to the form field.
According to everything I've read, if I return "isEmpty" from isValid(), my error message should read "foo" and if i return "isMatch" then it should read "bar".
This is not the case I'm running into though. If I return false from is valid, no matter what i set $this->_error() to be, my error message displays "foo", or whatever I have at index[0] of the error messages array.
If I don't define errorMessages, then I just get the error code I passed back for the display and I get the proper one, depending on what I passed back.
How do I catch the error code and display the correct error message in my form?
The fix I have implemented, until I figure it out properly, is to pass back the full message as the errorcode from the custom validator. This will work in this instance, but the error message is specific to this page and doesn't really allow for re-use of code.
Things I have already tried:
I have already tried validator chaining so that my custom validator only checks for matches:
->setRequired("true")
->addValidator("NotEmpty")
->addErrorMessage("URL May Not Be Empty")
->addValidator([*customValidator]*)
->addErrorMessage("X and Y urls may not be the same")
But again, if either throws an error, the last error message to be set displays, regardless of what the error truly is.
I'm not entirely sure where to go from here.
Any suggestions?
I think you misinterpreted the manual. It says
addErrorMessage($message): add an
error message to display on form
validation errors. You may call this
more than once, and new messages are
appended to the stack.
addErrorMessages(array $messages): add
multiple error messages to display on
form validation errors.
These functions add custom error messages to the whole form stack.
If you want to display validation error messages when the validation fails, you have to implement the message inside your validator.
ie.
const EMPTY = 'empty';
protected $_messageTemplates = array(
self::EMPTY => "Value is required and can't be empty",
);
public function isValid($value)
{
if(empty($value)) {
$this->_error(self::EMPTY);
return false;
}
return true;
}
This way, after the validation fails, you can get the error codes using $validator->getErrors() and the error messages using $validator->getMessages().
If you have the $_messageTemplates properly defined, Zend_Form automatically uses the error messages instead of error codes and prints them out.
Hope this helps.