I'm new to Struts 2 and facing this problem in keeping the layout of my page:
<s:form action="abc.action"><br>
<s:textfield key="name" label="Name" /><%--here I need to display errormessage for `name`--%>
<br>
<s:textfield key="email" label="Email" /><%--here I need to display errormessage for `email`--%>
<br>
<s:submit>
</s:form>
I'm using xml-validator for my action class, this works fine. but the validation-error messages appear over the fieldname and text-box. but i want it to come afterwards respective text-box (inside another html-container). Kindly advise.
If you're used to writing HTML, switch to the simple theme.
In struts.xml is probably the best place:
<struts>
<constant name="struts.ui.theme" value="simple" />
</struts>
Then just use the fielderror tag to put the error for the field where you want it.
It's a good to be familiar with the Struts2 tags: http://struts.apache.org/release/2.3.x/docs/tag-reference.html
That is the default according to Struts2 default templating. To change it, see http://www.mkyong.com/struts2/working-with-struts-2-theme-template/
You Can also Use Struts2 validation Framework
Validation framework comes with set of useful routines to handle form validation automatically and it can handle both server side as well as client side form validation. If certain validation is not present, you can create your own validation logic by implementing java interface.
com.opensymphony.xwork2.Validator
Validator uses XML configuration files to determine which validation routines should be installed and how they should be applied for a given application. validators.xml file contains all common validators declaration. If validators.xml file is not present in classpath, a default validation file is loaded from path
com/opensymphony/xwork2/validator/validators/default.xml
Validators Scope
There are two types of Validators in Struts2 Validation Framework.
Field Validators
Non-field validators
Field validators, as the name indicate, act on single fields accessible through an action. A validator, in contrast, is more generic and can do validations in the full action context, involving more than one field (or even no field at all) in validation rule. Most validations can be defined on per field basis. This should be preferred over non-field validation wherever possible, as field validator messages are bound to the related field and will be presented next to the corresponding input element in the respecting view.
<validators>
<field name="bar">
<field-validator type="required">
<message>You must enter a value for bar.</message>
</field-validator>
</field>
</validators>
Non-field validators only add action level messages. Non-field validators are mostly domain specific and therefore offer custom implementations. The most important standard non-field validator provided by XWork is ExpressionValidator.
<validators>
<validator type="expression">
<param name="expression">foo lt bar</param>
<message>Foo must be greater than Bar.</message>
</validator>
</validators>
For whole detail example visit this link link to struts2 validation
Related
Is there a way to dynamically add an attribute to a struts 2, tag UI tag such as a textfield?
The reason is that I want to add a readOnly form field attribute to an <s:textfield/>, depending on an action's method result. I cannot use readOnly="%{isReadOnly()}" since once the attribute is defined, the form element is read-only, no matter what value it has. And wrapping each form field into an <s:if/> tag is pretty cumbersome and results in a lot of code duplication.
I would also like to avoid JavaScript for interoperability reasons and for not relying on the browser's scripting settings.
If the issue is to use the built in struts2 functionality then one easy option is to render your view with freemarker, which readily supports the dynamic addition of attributes.
If you are using conventions, it is VERY trivial you just need to create a file with a ".ftl" extension, if you are using xml it is also very easy just use the freemarker result type (see here for greater description):
<action name="test" class="package.Test">
<result name="success" type="freemarker">/WEB-INF/content/testView.ftl</result>
</action>
Here is example view using a map to dynamically add attributes (example also taken from liked page):
<#s.textfield name="test" dynamicAttributes={"placeholder":"input","foo":"bar"}/>
The dynamicAttributes would be extremely useful in all JSP UI tags but alas it is not currently implemented.
NOTE: There is one error/omission in the above link. It tells you to add the following line which causes an error in my environment (simply the line is not needed).
<#assign s=JspTaglibs["/WEB-INF/struts.tld"] />
That is, this line in a file all by it self is sufficient for rendering a text element, no explicit tag library declaration needed!
<#s.textfield name="test" dynamicAttributes={"placeholder":"input","foo":"bar"}/>
There are a number of advantages to using freemarker over plain JSPs, so taking a moment to explore the syntax and using it for this one case may prove useful later.
I have a JSF form with number of fields. PrimeFaces normally does validation in this way:
http://www.primefaces.org/showcase-labs/ui/pprAjaxValidations.jsf
But I have more than 30 fields in my JSF form, so if I did this validation, it does not look good. How can I provide only a single message like "Please fill missing values" for any field if it is missing?
Your could render the message conditionally based on FacesContext#isValidationFailed().
<h:outputText value="Please fill out missing values" rendered="#{facesContext.validationFailed}" />
Note that this would only make sense if you have only the required="true" validation enabled and you thus don't use any converters or other more specific validators for which the enduser would of course like to see a more specific message.
I have used Struts2 in a period time, but I am still very confused with Struts2 Validation.
I have used xml-validation, or method addFieldError() to validate, but when I first come to input form-page, a page with struts-tags, and a <s:form>, I can not just go to this page by a href-link, I must go through another action, I read that page jsp with struts-tags must come from a action.
And I usually create a Action just for redirect to this input page, in execute() method just "success" and the role of this action is to go to input page legally, and in action which process the input form input-page, I choose the "input" result is still this input page.
So, I feel uncomfortable to do this, I always have a GoToSiteAction, just first-time go to input page.
So, I really need your help!!.
Use the with input fields , create a action and create a validation xml file with same name as java file name
For example : AddInput.java
xml file: AddInput-validation.xml
put it in same package.
write all the validations you need for the form in xml file like this.
<field name="U_Id">
<field-validator type="requiredstring" short-circuit="true">
<message>Affiliate Id cannot be empty</message>
</field-validator>
</field>
<field name="Password">
<field-validator type="requiredstring" short-circuit="true">
<message>Password cannot be empty</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">5</param>
<param name="maxLength">30</param>
<message>Password cannot be less than 5 or more than 30</message>
</field-validator>
</field>
When you hit the action it will first hit the validation xml and check for the validation then process the action class part.
You are not using or not using the struts2-conventions plugin to it's full effect. Please see: http://struts.apache.org/2.1.6/docs/convention-plugin.html search this page for the string "Examples of Action and Result to Template mapping" and consider the table which follows.
In the future after adding the struts2-conventions-plugin jar to your project add the postfix "-input" to the end of all future forms.
Say we created a form to add a new employee:
/WEB-INF/content/add-employee-input.jsp
The struts2 form tag would reference an action simply called "add-employee" in a java class probably named something like com.mypackages.struts2.AddEmployee then if the add-employee action validation fails then "input" is returned and the "add-employee-input" form is again rendered. However we do not need to create a "add-employee-input" action, the conventions plugin will do this for us automatically... as such we can directly enter the form if we wish by referencing it and this is very convenient.
Try it out and you'll see what I mean.
It's very handy to use bean validation like javax.validation.constraints.Size in my Java code, such as:
#Size(min=1,max=30)protected String custName;
rather than the wordier equivalent embedded in the .xhtml page, such as:
<f:validateLength minimum="1" maximum="30" />
The problem I'm having is that I'm not able to get the field name to appear in the error message. I can customize the message by adding the following entry to ValidationMessages.properties in the root of my source directory:
javax.validation.constraints.Size.message={0} value is too long.
But no value gets substituted for {0}. The upshot is that while the annotated validators work fine for simple pages where I can include a separate <p:message /> for each form field, they don't work so well for a more complex (e.g. tabbed) form where I need to group my messages at the top of the page. Is there any workaround for this, or is my only reasonable choice to use the JSF validators?
The {0} is represented by the label attribute of the input component in the view side, which defaults to client ID when unspecified.
E.g.
<h:inputText value="#{bean.customer.name}" label="Customer name">
You also need to override the JSF's default format for bean validator messages. You need to add the following entry to JSF message bundle as specified in <message-bundle> of faces-config.xml:
javax.faces.validator.BeanValidator.MESSAGE = {1} {0}
In this specific entry, the {1} will be the label of the JSF input component and {0} will be the message of the bean validator.
I have what I'd think is a common issue but an entire day of googling hasn't turned up anything useful.
I have a form with a checkbox and a textfield. I'd like to do a regex validation of the textfield, but only if the checkbox is selected. Regex validation is currently working for other non-conditional fields but I can't for the life of me figure out if there is a syntax that allows for this in the action-validation.xml file. ie. I have something like below for other fields. What I need is a way of making this conditionaly evaluated only if the checkbox is selected.
<validators>
<field name="sn">
<field-validator type="regex" >
<param name="expression">
[0-9]{12}
</param>
<message>Serial number format is invalid. Please try again</message>
</field-validator>
</field>
</validators>
Does anyone have a code example of how to do this?
Any help is much appreciated.
For Struts 1 there was a validation rule called "validwhen" that you could use to perform complex validations, but for Struts 2, as far as I know there is no such validation.
For Struts 2 you could go with the Expression Validator in which you can specify an OGNL expression to use, so I guess you could try something like this:
<validator type="expression">
<param name="expression">checkboxField eq "selected" and inputText eq "bla"</param>
<message>....</message>
</validator>
One thing I don't know is if there is a easy way of doing your regular expression check using OGNL (you'll have to look into it).
Additionally, if that does not work, you can always write your own custom validator.
The expression and fieldexpression validators take an OGNL expression. Evaluating to true passes false fails. You can use them quite easily for this requirement.
Personally I would just use the built in validators via XML like you're doing and then implement any custom validation logic in the validate() method (or methodname-validate() method). Just preference, no good reason really.