Halaman

Subscribe:

Main Menu

Jumat, Juli 25, 2008

Struts2 Validation

Validasi di struts2 ternyata cukup mudah ya :D. baru ngerti enaknya pake struts :). ada dua jenis tipe validasi di struts 2. cara pertama yaitu pake XML dan kedua pake annotation.

Untuk validasi Struts2 memakai XML cukup membuat XML dengan nama yang sama dengan java class yang akan di validasi di tambahkan dengan "-validation". misalnya jika nama java class nya "Login" maka nama XML validasi nya "Login-validation.xml". terus tinggal kita isi XML validasinya sesuai dengan field atau properties dari java class nya. misalnya seperti ini. kita punya sebuah class namanya Login dg field/propeties username dan password dg masing2 bertipe String. maka XML validasinya akan seperti ini..


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
<field name="username">
<field-validator type="requiredstring">
<message>Username is required</message>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message>Password is required</message>
</field-validator>
</field>
</validators>

Seharusnya begini saja sudah cukup :). nanti saat user nginputkan nilai null atau gak ada isinya. akan muncul pesan error :).

Untuk Validasi Struts 2 pake Annotation Lihat aja ini :)





















































































Annotation Description
ConversionErrorFieldValidator Annotation Checks if there are any conversion errors for a field.
DateRangeFieldValidator Annotation Checks that a date field has a value within a specified range.
DoubleRangeFieldValidator Annotation Checks that a double field has a value within a specified range.
EmailValidator Annotation Checks that a field is a valid e-mail address.
ExpressionValidator Annotation Validates an expression.
FieldExpressionValidator Annotation Uses an OGNL expression to perform its validator.
IntRangeFieldValidator Annotation Checks that a numeric field has a value within a specified range.
RegexFieldValidator Annotation Validates a regular expression for a field.
RequiredFieldValidator Annotation Checks that a field is non-null.
RequiredStringValidator Annotation Checks that a String field is not empty.
StringLengthFieldValidator Annotation Checks that a String field is of the right length.
StringRegexValidator Annotation Invokes a regular expression to validate a String field.
UrlValidator Annotation Checks that a field is a valid URL.
Validation Annotation Marker annotation for validation at Type level.
Validations Annotation Used to group validation annotations.
VisitorFieldValidator Annotation Invokes the validation for a property's object type.
CustomValidator Annotation Use this annotation for your custom validator types.


Source : http://struts.apache.org/2.0.11.2/docs/annotations.html

1 komentar: