Spring Validation Displaying Custom Message - spring

Validation in Spring 3.x using #Valid annotation:
Below is snippet from the messages_en.properties. I have a form having Username and Password field. When user does not enter anything in Username field, it displays both these messages one below other.
NotEmpty.loginBean.username=Username cannot be Empty
Size.loginBean.username=Size must between 5 to 50 characters.
Any HTML tag given in the message.properties is not interpreted.
NotEmpty.loginBean.username=<li>Username cannot be Empty</li>
Above would display <li> as it is.
Questions:
1) Is there any ways to interpret HTML tag and display its output?
2) Can i show single message though both validation fails?

Ad. 1) Yes, use htmlEscape="false":
<form:errors path="nip" cssClass="error" htmlEscape="false" />
Ad. 2) This is actually JSR303's Achilles' heel - it can be done, but is neither easy nor clean (see this issue). Order of validating each annotated field is undefined, so trick is to use #GroupSequence and custom groups like described here or here.
Alternative solution would be to use custom annotation with #ReportAsSingleViolation, but it will not distinct NotEmpty and Size errors as it'll have its own error message.

Related

individual error message for each jsf validator tag

I have an input field which must meet the following restrictions: the input data should have exactly 2 characters, it should accept only letters and numbers, and it must be uppercase. So far, i did the following:
<h:inputText id="code" >
<f:validateLength minimum="2" maximum="2" />
<f:validateRegex pattern="^[a-zA-Z0-9]*$"/>
<f:validateRegex pattern="^[A-Z0-9]*$"/>
</h:inputText>
However, i need individual error messages when any of these validations fails. I did some search, and i found the following UNsuitable solutions:
1) How to customize JSF validation error message : Providing an validatorMessage attribute inside the text tag won't do the job, because this way i can provide only one message per input text tag.
2) http://incepttechnologies.blogspot.ro/p/validation-in-jsf.html : Validation method in the backing bean, or imperative validation using #FacesValidator annotation, are not good because this is exactly what i try to avoid; i want to move validation from back-end to front-end
3) https://www.mkyong.com/jsf2/customize-validation-error-message-in-jsf-2-0/ : overriding the error message in messages.properties is not good for two reasons: 1. I want to use custom error messages only locally (page scope), not for the entire application. 2. I have the same validator tag occuring twice - but with different patterns, and i want a different error message for each situation
The documentation for the validation tags (http://docs.oracle.com/javaee/6/javaserverfaces/2.0/docs/pdldocs/facelets/ and http://docs.oracle.com/javaee/6/javaserverfaces/2.0/docs/pdldocs/facelets/f/validateLength.html) specifies no attribute such as 'message', or 'errorMessage', as I hoped.
I have not tFied Kt but I think a woraround will be to place the custom overridden validation messages in a locale specific (which can be used only for this case ) properties file and use locale attribute of f:view tag to set the locale at the page level so that the messages are displayed from the locale specific message bundle.
A temporary solution is to concatenate all error messages into one big message. In case any validation fails, the corresponding message is anyway included in the big message.
So i made use of the validatorMessage attribute in the inputText tag.
Also, in order not to get the large message multiple times (when more than one of the validations fails) i replaced the 3 validations with an equivalent one:
<f:validateRegex pattern="^[A-Z0-9]{2}$"/>

OmniFaces validateOrder disabling

I'm trying to use validateOrder component to validate two java.util.Date objects. It is similar to showcase example on this link (PrimeFaces example). Everything works perfect, but i have one question:
What if 2nd date field is not required?
In that case i'm getting nullpointer exception, and since validateOrder has "disabled" attribute, i was wondering is it worth/possible enabling/disabling it via ajax every time the 2nd date is inserted/removed. If not, i guess i'll stick to Balus' approach for JSF2.0 cross-field validation that you can read about on this link.
Let the disabled attribute check if the 2nd field is filled in. If it's not filled in, the request parameter value associated with field's client ID will be empty. Use exaclty that to let disabled attribute evaluate to true.
<p:calendar ... binding="#{endDate}" />
...
<o:validateOrder ... disabled="#{empty param[endDate.clientId]}" />
Code is as-is. No additional backing bean property necessary for binding.
See also:
How does the 'binding' attribute work in JSF? When and how should it be used?

Freemarker Checkboxes input in Spring form

I have an HTML form bound to a Spring model to take in user data and add it to a database. This works fine. I have used Spring Freemarker macros for the fields to take input and validate before sending, e.g.
<#spring.formInput path="myForm.username"/>
<#spring.showErrors ", "/>
This also works fine for text input. What is causing me problems is rendering multiple checkboxes with the Spring macro. My original HTML was:
<input name="roleList" type="checkbox" value="1"/>Adminstrator
<input name="roleList" type="checkbox" value="2"/>Developer
<input name="roleList" type="checkbox" value="3"/>Customer
I created a Java Map<String, String> of this information with the keys as "1", "2", "3" in my controller method and added it to the model, then replaced the HTML with this macro in my ftl template:
<#spring.formCheckboxes path="quickForm.roleList" options="${roleMap}" separator="<br>"/>
But I get an error
Expecting a string, date or number here, Expression roleMap is instead a freemarker.template.SimpleHash
Why would it give that message if it requires a Map? (as in the Spring Docs for FreeMarker macros) Can anyone explain how I should be providing the checkbox data?
Finally worked this out, so for anyone who's interested: it wasn't as straightforward as just creating a HashMap of values and adding them with model.addAttribute("roleMap", myHash) - I had to create a service class to do this instead: it retrieved my list of roles from a database table and then converted them into a HashMap<String, String>. I then called this in my controller method, added it to my model (called "roleMap" here) and used it within my FreeMarker template without the usual formatting, like this:
<#spring.formCheckboxes path="quickForm.roleList" options=roleMap separator="<br>"/>
Having the data converted in a service method was key for Spring to use it as checkbox options.

Organize validation messages in Struts2 validation(XML)

I am trying to do validations in struts 2 for my current project. I have to group my validation messages. For Eg: If there are 3 fields that are empty and there are 3 other fields whose format is not right, I need to get a msg like
"The following fields are required: field1, field2, field3
The format of the following fields are invalid: field4, field5, field6"
I tried providing a param to fieldError.
Eg:
< s : fielderror >
< s : param value="%{requiredstring}"/>
< / s : fielderror>
According to me this is like specifying "show all errors whose validator type is requiredstring". Please correct me if I am wrong.
But this will display the message "The following fields are required" each time for every field that is empty. I want it displayed only once.
Is there a way to do this cleanly in stuts2 using validation through xml? I donot want to do all the validations in a validate method.
Thanks
You are wrong; I have no idea why you thought that'd work, the docs don't imply that's possible.
Field errors are just that--errors for a specific field. If you need to group errors by arbitrary criteria, like the validation type, you'll need to implement that yourself.
There are a number of ways to do this, including writing a custom validation interceptor, providing validators that group errors in a different way, or simply gathering the appropriate messages in an action or validation method.
You could gather errors based on the message content, but IMO that would be brittle. If this is a cross-application issue, you're better off doing it a different way.
All that said, by presenting error messages in an order not necessarily reflective of the form, you're pushing more cognitive overhead onto the user: I don't want to see groups of messages telling me which fields share the same error, I want to see what's wrong with each field, in the same order the fields are presented on the form, preferably near the form field itself.

Validate field and throw exception in JSF, but attach error message to another field?

I have some fields on my page which I want cross-validated. But I don't want error from this validation to be displayed in <h:message> for this fields.
If I add validator to any of the fields, and validator throws exception, error is displayed in <h:message> for this field. On the other hand I HAVE TO throw exception if I want to suppress page from submitting. Just displaying some error message is not enough.
So I created some hidden field on the form, and attached validator there. This validator has access to UIComponents of the fields I want to validate, so it can validate them. When validator throws exception, error shows in <h:message> for hidden field, which I can place anywhere I want.
Everything works, if I put hidden field after the fields I want to validate. (If I put it before, hidden field validation is triggered before even UIComponents of my fields are updated).
The problem is it's nasty hack :) Is there some better way to do it?
The problem is it's nasty hack :) Is there some better way to do it?
Not for the particular functional requirement. It's very true that JSF allows very little fine grained control for cross-validation of multiple fields.
Everything works, if I put hidden field after the fields I want to validate. (If I put it before, hidden field validation is triggered before even UIComponents of my fields are updated).
Components are during validations phase processed in the order as they appear in the component tree. If you have at some point an UIInput at hands which is still to be processed yet, then you need to grab the submitted value by UIInput#getSubmittedValue(). If it is already been processed, then you need to grab the submitted (and converted and validated) value by UIInput#getValue() instead.
So, if you put the hidden field with the validator after the to-be-validated components, then you need UIInput#getValue() to grab the values. If the hidden field is put before the to-be-validated components, then you need UIInput#getSubmittedValue() to grab the values.
i have got this code working for me:
throw new ValidatorException(new ArrayList());
no errors were displayed.

Resources