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.
Related
I have a JSP which has below tags the data in resultsList fed in some action and forwarded to below jsp here I would like to get the data back into the other action based on the checkbox selection. Please help, can do using Struts1 but don't like to turn back to Struts1 since started using Struts2.
<display:table class="displaytag" id="row" style="font-size:1.4em;" name="resultsList" requestURI="/SomePath.action">
<display:column property="businessType" title="Business Type"></display:column>
<display:column property="structure" title="Structure"></display:column>
<display:column property="tradeSubType" title="Trade Sub Type"></display:column>
<display:column property="businessGroup" title="Business Group"></display:column>
<display:column title="Select To Copy" align="center">
<s:checkbox name="selectToCopy" fieldValue="false" value="false" label="Check Me To Download"></s:checkbox>
</display:column>
</display:table>
The data will be fetched in one action and forwarded to the jsp where jsp contains above display tag and now I need to submit the form and action should receive the checked information to process further. Any help here is really appreciated, I can do it using Struts1 no doubt but would like to continue in Struts2.
I'm guessing your action class sends some domain objects from this type:
public class MyData {
private Integer id;
private String businessType;
//other params
//getter/setters
}
And your action class, that ist invoked before accessing the displaytag jsp page has a list of objects form type MyData:
public class MyDisplayTagAction extends ActionSupport {
private List<MyData> myDataList;
//other params
//getter/setter
public String execute() {
myDataList = getMyDataListFromSomewhere();
return SUCCESS;
}
}
The JSP should contain a form and a submit button. Moreover you have to define every data you want to send back as a field in that form. If the user is not allowed to change them, use hidden fields. The #attr.row.id access printing that id to the value. #attr is from ognl to access the variable row defined from displaytag. (For more info: Struts OGNL)
<s:form action="myStrutsPostAction" method="post">
<display:table name="myDataList" uid="row">
<display:column>
<s:checkbox name="resultsList[%{#attr.row_rowNum - 1}].selectToCopy" id="check%{#attr.row_rowNum - 1}" value="%{#attr.row.selectToCopy}"/>
</display:column>
<display:column>
<input type="hidden" name="resultsList[<s:property value='%{#attr.row_rowNum - 1}'/>]" value="<s:property value='%{#attr.row.businessType}' />"/>
<s:property value="%{#attr.row.businessType}"/>
</display:column
</display:table>
<s:submit>
</s:form>
The post action class (the one that takes the form request) should contain a list, that was defined in the <s:form> and struts will set only the the data into this list.
public class MyPostAction extends ActionSupport {
private List<MyData> resultsList = new ArrayList<>();
//getter/setter
}
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;
});
});
I have lots of number field let say num1, num2 ...
Now I am looking for way I can apply a set of validation on all field rather than writing same validations multiple times.
Here is set of two validation for requiredString and Number check
<validators>
<field name="num1">
<field-validator type="requiredstring">
<message>Field cannot be left blank</message>
</field-validator>
<field-validator type="regex" short-circuit="true">
<param name="expression"><![CDATA[^[0-9]+$]]></param>
<message>Not a valid Number</message>
</field-validator>
</field>
</validators>
Tia
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>
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