Zend_Validate_Abstract custom validator not displaying correct error messages - zend-framework

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.

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?

Outlook Addin Event handler clean up

I am having problems with the event handler in my office addin . Below is an example code i got from microsoft website to explain what i mean.
I have a manifest file that uses the on-send hook as well as a click-based event triggering.
My button calls appendMessageBodyOnClick and onsend i call appendMessageBodyOnSend. Both function primarily do the same thing. I never want to block sending emails regardless.
The problem is that the event object is not properly cleaned up i think.
Scenario 1
When i click my button ; which calls event.completed(), and then after i try to send the message, it says my app is blocking the message, but then when i try to send again it goes through.
Scenario 2
When i leave the subject empty and then send the message, as expected i am prompted that the subject is empty. If i cancel sending the message on this note and then click on my button, the message tries to send as though i clicked send.
I am supposing the is some sort or state clean up issue. What am i doing wrong here?
Function-File.js
function appendMessageBodyOnClick(event) {
// Append string to message body
event.completed();
}
// In the following example, the checkMessage function has
// been registered as an event handler for ItemSend.
function appendMessageBodyOnSend(event) {
// Append string to message body
event.completed({allowEvent = true});
}
Not sure if this will help, but I also have faced some seemingly inconsistent behavior while understanding how to signal that event is fully completed. Once I got my edge cases fixed, then it worked.
One suggestion: Appending string to message body should be an async function. Call the event.completed() from inside the callback function. (i.e: make sure when you are calling event.completed(), nothing else is pending -like another async result)
Something like the following:
Office.context.mailbox.item.body.setAsync("new body", function(asyncResult) {
// handle success and failure
event.completed()
});
Same would be for your scenario 2, make sure event.completed() is called at the very end.

Access 2010 - Unlock form during OnError Event Procedure

I have a form with multiple required fields. I have error handling in my Save function to handle when one of these fields is empty, so the user only recieves the error (error 3314) when trying to save the record (This handling has no problems and works fine by itself).
However, sometimes (usually if a required field has been "dirty" and then cleared) a Form error 3314 occurs, which doesn't let you click anywhere until you've typed something into the field.
I tried to ignore this error by setting form's OnError property to the following event procedure:
Private Sub Form_Error(DataErr As Integer, Response As Integer)
Const conBlankField = 3314
If DataErr = conBlankField Then
Response = acDataErrContinue
End If
End Sub
According to other resources I've found, acDataErrContinue is supposed to ignore the error, but it doesn't seem to do so. While it does prevent the default Access error message from popping up, the form is still "locked" until something is typed into the field.
Is there a way to force the form to ignore this error completely, so error 3314 is handled exclusively by the error handling in my Save function?

MVC jquery ajax form server side validations

We have a number of forms on our site that are shown with jquery .dialog and we submit them using an ajax post request.
I've done a fair bit of research and from what I can tell there isn't any definite patterns on how to return validation errors from the server side as a result of an ajax request.
Pretty much the only pattern I could find was to post the form and then do validation server side and in either case return a json object that encapsulated a result and if the result was incorrect the form html
ie.
{result: true}
{success: false, html = "<form>....</form>"}
So in the case the result was false you would need to rewire up any events attached to items on the form as you would be replacing the old form with the new form that has the validation errors.
This seems like an ok approach but you also end up potentially returning a lot more data to the client that you need to when they only really need to validation messages and you are also forced to rewire the form up which is a bit annoying.
I did find one other mention of somehow getting the validation errors and returning them in a json object from the action and somehow telling the client to display them against the correct fields.
Is there any frameworks out there that make this easier or should I write my own or just stick to returning the entire partial for the form and rewiring it when validation is incorrect?
I don't know of any frameworks that handle this particular case–and I don't know that there's a clear best practice–but it's easy enough to serialize validation errors and return them as a JSON object. You could try this extension method on ModelStateDictionary:
public static IEnumerable<ValidationResult> GetValidationResults(this ModelStateDictionary dictionary)
{
foreach (var key in dictionary.Keys)
foreach (var error in dictionary[key].Errors)
if (error != null)
yield return new ValidationResult(error.ErrorMessage, new string[] { key });
}
And in the controller:
if (!ModelState.IsValid)
{
return new JsonResult(ModelState.GetValidationResults());
}
But you're right, you would then have to loop through the object and append the errors to the correct fields. If you have ClientValidationEnabled and UnobtrusiveJavaScriptEnabled set to true, the loop would look something like this:
$.each(errors, function(i, item) {
$('span[data-valmsg-for=' + item.MemberNames[0] + ']').html(item.ErrorMessage);
})
If not, it wouldn't be that difficult to match up the error messages to their respective fields as the object contains the field name. This would definitely save you some data across the wire, but it moves a larger share of the validation responsibility into Javascript. Like I said, I don't know that there's a clear best practice, but I have used this method in the past with success.

Zend Validate, Display one message per validator

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