Struts2 xml validation for checkbox not for checboxlist - struts2

I have one form containing one checkbox(not checkbox list)and one textfield.
If the checkbox is cheked then no need to enter the value for textfield.
If the check box is not checked then I need to validate the textfield has mandatory.
How can I do using expression validator.Is this Possible in struts2.0.11.
Let me know
Thanks in advance

Use fieldexpression validator. Example :
SomeAction.java
private SomeObject object; // with getter & setter
private boolean doNotCheck; // with setter
input.jsp
<s:textfield name="object.field" />
<s:checkbox name="doNotCheck" />
<s:fielderror fieldName="object.field" />
SomeAction.validation.xml
<validators>
<field name="object.field">
<field-validator type="fieldexpression">
<param name="expression">
<![CDATA[ isDoNotCheck() ? true : (object.field != null && !object.field.isEmpty()) ]]>
<!-- OR -->
<!-- isDoNotCheck() ? true : !object.field.isEmpty() -->
</param>
<message>This is a mandatory field</message>
</field-validator>
</field>
</validators>

You can implement validate() method in your action class and add the validation code in it.
For details, please read the docs.
http://struts.apache.org/2.x/docs/form-validation.html
Another option is xml validation.
http://struts.apache.org/2.x/docs/validation.html

Related

JSF: f:viewParam doesn't call setter, f:viewAction doesn't call business-method [duplicate]

Can anyone clarify how we can use in general, or a in real world example, this snippet?
<f:metadata>
<f:viewParam id="id" value="#{bean.id}" />
<f:viewAction action="#{bean.init}" />
</f:metadata>
Process GET parameters
The <f:viewParam> manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>, but then for GET parameters.
The following example
<f:metadata>
<f:viewParam name="id" value="#{bean.id}" />
</f:metadata>
does basically the following:
Get the request parameter value by name id.
Convert and validate it if necessary (you can use required, validator and converter attributes and nest a <f:converter> and <f:validator> in it like as with <h:inputText>)
If conversion and validation succeeds, then set it as a bean property represented by #{bean.id} value, or if the value attribute is absent, then set it as request attribtue on name id so that it's available by #{id} in the view.
So when you open the page as foo.xhtml?id=10 then the parameter value 10 get set in the bean this way, right before the view is rendered.
As to validation, the following example sets the param to required="true" and allows only values between 10 and 20. Any validation failure will result in a message being displayed.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
</f:metadata>
<h:message for="id" />
Performing business action on GET parameters
You can use the <f:viewAction> for this.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
<f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />
with
public void onload() {
// ...
}
The <f:viewAction> is however new since JSF 2.2 (the <f:viewParam> already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event> instead.
<f:event type="preRenderView" listener="#{bean.onload}" />
This is however invoked on every request. You need to explicitly check if the request isn't a postback:
public void onload() {
if (!FacesContext.getCurrentInstance().isPostback()) {
// ...
}
}
When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:
public void onload() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
// ...
}
}
Using <f:event> this way is in essence a workaround/hack, that's exactly why the <f:viewAction> was introduced in JSF 2.2.
Pass view parameters to next view
You can "pass-through" the view parameters in navigation links by setting includeViewParams attribute to true or by adding includeViewParams=true request parameter.
<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">
which generates with the above <f:metadata> example basically the following link
<a href="next.xhtml?id=10">
with the original parameter value.
This approach only requires that next.xhtml has also a <f:viewParam> on the very same parameter, otherwise it won't be passed through.
Use GET forms in JSF
The <f:viewParam> can also be used in combination with "plain HTML" GET forms.
<f:metadata>
<f:viewParam id="query" name="query" value="#{bean.query}" />
<f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
<label for="query">Query</label>
<input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
<input type="submit" value="Search" />
<h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
...
</h:dataTable>
With basically this #RequestScoped bean:
private String query;
private List<Result> results;
public void search() {
results = service.search(query);
}
Note that the <h:message> is for the <f:viewParam>, not the plain HTML <input type="text">! Also note that the input value displays #{param.query} when #{bean.query} is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).
See also:
ViewParam vs #ManagedProperty(value = "#{param.id}")
Communication in JSF 2.0 - Processing GET request parameters
Send params from View to an other View, from Sender View to Receiver View use viewParam and includeViewParams=true
In Sender
Declare params to be sent. We can send String, Object,…
Sender.xhtml
<f:metadata>
<f:viewParam name="ID" value="#{senderMB._strID}" />
</f:metadata>
We’re going send param ID, it will be included with “includeViewParams=true” in return String of click button event
Click button fire senderMB.clickBtnDetail(dto) with dto from senderMB._arrData
Sender.xhtml
<p:dataTable rowIndexVar="index" id="dataTale"value="#{senderMB._arrData}" var="dto">
<p:commandButton action="#{senderMB.clickBtnDetail(dto)}" value="見る"
ajax="false"/>
</p:dataTable>
In senderMB.clickBtnDetail(dto) we assign _strID with argument we got from button event (dto), here this is Sender_DTO and assign to senderMB._strID
Sender_MB.java
public String clickBtnDetail(sender_DTO sender_dto) {
this._strID = sender_dto.getStrID();
return "Receiver?faces-redirect=true&includeViewParams=true";
}
The link when clicked will become http://localhost:8080/my_project/view/Receiver.xhtml?*ID=12345*
In Recever
Get viewParam
Receiver.xhtml
In Receiver we declare f:viewParam to get param from get request (receive), the name of param of receiver must be the same with sender (page)
Receiver.xhtml
<f:metadata><f:viewParam name="ID" value="#{receiver_MB._strID}"/></f:metadata>
It will get param ID from sender View and assign to receiver_MB._strID
Use viewParam
In Receiver, we want to use this param in sql query before the page render, so that we use preRenderView event. We are not going to use constructor because constructor will be invoked before viewParam is received
So that we add
Receiver.xhtml
<f:event listener="#{receiver_MB.preRenderView}" type="preRenderView" />
into f:metadata tag
Receiver.xhtml
<f:metadata>
<f:viewParam name="ID" value="#{receiver_MB._strID}" />
<f:event listener="#{receiver_MB.preRenderView}"
type="preRenderView" />
</f:metadata>
Now we want to use this param in our read database method, it is available to use
Receiver_MB.java
public void preRenderView(ComponentSystemEvent event) throws Exception {
if (FacesContext.getCurrentInstance().isPostback()) {
return;
}
readFromDatabase();
}
private void readFromDatabase() {
//use _strID to read and set property
}

struts2 validator expression

Is possible to make this conditional expression validation?:
(invitation.id==null and (newText==null or newText.isEmpty()))
I've tried several ways, several times, but don't achieve it.
This version is working, but on server-side, and ignore if invitation.id is null or empty... any ideas???:
<field name="newText">
<field-validator type="fieldexpression">
<param name="expression">!(invitation.id eq null and (newText eq null or newText.empty))</param>
<message>${getText("validation.required")}</message>
</field-validator>
</field>
http://struts.apache.org/release/2.2.x/docs/fieldexpression-validator.html
what is wrong with the expression?? Thanks!
Your problem is that you are trying to validate another field (invitation.id) into the newText Field Validator (i don't think it's possible, but I'm not sure).
However, you could split it into two validators, raising the message corrispondent to the failure case, that is more correct imho;
<field name="invitation.id">
<field-validator type="required">
<message>${getText("validation.invitation.id.required")}</message>
</field-validator>
</field>
<field name="newText">
<field-validator type="fieldexpression">
<param name="expression">
<![CDATA[
newText != null && !newText.trim().empty())
]]>
</param>
<message>${getText("validation.newText.required")}</message>
</field-validator>
</field>
, if you need to trim it, otherwise it could become simply
<field name="invitation.id">
<field-validator type="required">
<message>${getText("validation.invitation.id.required")}</message>
</field-validator>
</field>
<field name="newText">
<field-validator type="requiredString">
<message>${getText("validation.newText.required")}</message>
</field-validator>
</field>
Note that required is for every non-text fields, while requiredString is for text fields only.
Expression Validator is very powerful, but it should be used for more complex purposes:
for example, if you want to validate a Date against another one dynamically read (through a Getter) from your Action; lets say you've previously chosen a User, and you need to validate a date from the page against the user Start and End Validity interval; but you want to pass the validation too if the date is not inserted, because it is already handled by the required validator (so you won't raise two messages):
<field name="inputDate">
<field-validator type="required">
<message><![CDATA[ Input Date is mandatory ]]></message>
</field-validator>
<field-validator type="fieldexpression">
<param name="expression">
<![CDATA[
inputDate==null ||
(inputDate >= chosenUser.startValidity
&&
inputDate <= chosenUser.EndValidity
)
]]>
</param>
<message>
<![CDATA[Input Date must be included in the User Validity interval
(from ${chosenUser.startValidity} to ${chosenUser.endValidity} )
]]>
</message>
</field-validator>
</field>
where chosenUser is an User object from your Action (public User getChosenUser())
and startValidity and endValidity are properties of the User object (public Date getEndValidity()).
And as you can see, the dynamic read can be performed in messages too... this is how powerful expression validator is ;)
First of all expression is not a valid parameter. If you really want to validate on client side, try to use java-script or jquery for validation. But you have to validate inputs on server - side also because sometimes user could disable the javascript .So in that case you can use struts2 - validation.
for detailed explanation refer http://viralpatel.net/blogs/struts2-validation-framework-tutorial-example/
Ok, finally I used client-side validation width jquery emulating struts2.
I don't like this for compatibility reasons, please if there is a way to do it in a standard way, I'll apreciate any help.
Removing struts validation:
<!--<field name="newText">
<field-validator type="fieldexpression">
<param name="expression">!((invitation.id==null or invitation.id.empty) and (newText==null or newText.empty))</param>
<message>${getText("validation.required")}</message>
</field-validator>
</field>-->
Adding js/jquery code:
function mySubmit() {
if ((invitationId==null || invitationId<0) && $("#text").val().trim()=='') {
var trStrutsFieldError='<tr errorfor="text">'+
'<td colspan="2" align="center" valign="top"><span class="errorMessage">'+strValidationRequired+'</span></td>'+
'</tr>';
$(trStrutsFieldError).insertBefore($("#text").parent().parent());
return false;
}
return true;
}
$(document).ready(function(){
$("form").submit(function(event) {
$.each($("form").find("span.errorMessage"), function() { /* <tr errorfor="title"><td colspan="2" align="center"><span classname="errorMessage" class="errorMessage">Campo requerido */
return false;
});
if ($(mySubmit).exists()) {
if (!mySubmit())
return false;
}
return true;
});
});

How to giving validation for dojo datetimepicker using struts validation xml

i trying to give validation to the dojo datetimepicker using struts 2 validation xml but no success if someone has gone through the same scenario do help me out
<s:label value="Joining Date"/>
<sx:datetimepicker name="joiningDate" displayFormat="dd/mm/yyyy"/>
and in the validation xml i write
<field name="joiningDate">
<field-validator type="required">
<message>Select Date.</message>
</field-validator>
</field>
problem is when i click submit the page submit even if the joinindate field is empty means validation field in not applied
Just add required Attribute to the tag.
i,e
<sx:datetimepicker name="joiningDate" displayFormat="dd/mm/yyyy" required="true"/>
it should work...!
Cheers
Karthikeyan
You can also use:
<field-validator type="date">
<param name="min">01/01/1990</param>
<param name="max">01/11/2012</param>
<message>Birthday must be within ${min} and ${max}</message>
</field-validator>

dynamic field name for field validator in struts2

i have this Class
public Class Employee
{
String name;
List<Address> listOfAddress;
}
public Class Address
{
String location;
String streetName;
}
in my JSP page i have filled like this
<s:textfield id="streetName" name="listOfAddress[%{listOfAddress.size()}].streetName" size="20" maxlength="24" cssStyle="width: 100px" />
each time i submit the page an object of time Address is added to the list therefore the size will increase by one.
when i view the source HTML of the previous textField, its name looks like this listOfAddress[0].streetName , if i submit the JSP page after succefull addition, it will return to the same page and the name of this textfield will be listOfAddress[1].streetName
if you view its HTML source
and like this i can add as many addresses as i want to same Employee object.
so far everything is OK. the problem is when i want to validate this field ican't because it is dynamic
if i put this validation it will validate it the first time only.
<field name="listOfAddress[0].streetName">
<field-validator type="requiredstring" short-circuit="true">
<param name="trim">true</param>
<message>sorry this field is required field</message>
</field-validator>
</field>
what i want is to make the index of the list "listOfAddress" dymanic according to the size of the list.
i don't know how to pass it dynamicall from the jsp
can i do something like this ?
<field name="listOfAddress[**${dynamic index value}**].streetName">
<field-validator type="requiredstring" short-circuit="true">
<param name="trim">true</param>
**<param name="myIndex">${dynamic index value}</param>**
<message>sorry this field is required field</message>
</field-validator>
</field>
or pass the dynamic value to a custom validator ?
please help me, how to validate the list when the index is dynamic
Use visitor validator. See http://struts.apache.org/2.x/docs/using-visitor-field-validator.html.

Struts2 Map/Collection Validation

I am trying to do validation on a Map using struts 2.
When I click on the submit button, the error message will always appear even though I have inserted a value into the textbox.
Is there anyway for it to work?
Any help will be much appreciated.
The following is my file
In my new.jsp
<s:textfield name="myObject.myMap['name']" key="name" ></s:textfield>
In the validaton.xml
<validators>
<field name="myObject.myMap['name']">
<field-validator type="requiredstring">
<message key="errors.required"/>
</field-validator>
</field>
</validators>

Resources