Thursday, 15 May 2014

struts2 validator expression -



struts2 validator expression -

is possible create conditional look validation?:

(invitation.id==null , (newtext==null or newtext.isempty()))

i've tried several ways, several times, don't accomplish it. version working, on server-side, , ignore if invitation.id null or empty... ideas???:

<field name="newtext"> <field-validator type="fieldexpression"> <param name="expression">!(invitation.id eq null , (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 wrong expression?? thanks!

your problem trying validate field (invitation.id) newtext field validator (i don't think it's possible, i'm not sure).

however, split 2 validators, raising message corrispondent failure case, more right imho;

class="lang-xml prettyprint-override"><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 need trim it, otherwise become simply

class="lang-xml prettyprint-override"><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 required every non-text fields, while requiredstring text fields only.

expression validator powerful, should used more complex purposes:

for example, if want validate date against 1 dynamically read (through getter) action; lets you've chosen user, , need validate date page against user start , end validity interval; want pass validation if date not inserted, because handled required validator (so won't raise 2 messages):

class="lang-xml prettyprint-override"><field name="inputdate"> <field-validator type="required"> <message><![cdata[ input date 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 included in user validity interval (from ${chosenuser.startvalidity} ${chosenuser.endvalidity} ) ]]> </message> </field-validator> </field>

where chosenuser user object action (public user getchosenuser()) , startvalidity , endvalidity properties of user object (public date getendvalidity()).

and can see, dynamic read can performed in messages too... how powerful look validator ;)

struts2

No comments:

Post a Comment