Home >> Struts
Writing own Validator using Struts2 Framework
In order to create or build own Validator while using Struts2,
I have followed following steps to create a simple String
Upper case Validator for just to look for initial Capital
Letter in the String that is entered in the Name field.
Extending an existing example that has a index page and
a preview page.
this example may be one out of many ways one can define
Validators in Struts2 Framework.
Steps as follows:
1. create your own Validator class that extends
com.opensymphony.xwork2.validator.validators.FieldValidatorSupport
2. implement validate (Object arg) method to add yours specific
validation rule/logic.
In this example: this method looks something like this:
|
|  |
|
package sample;
import com.opensymphony.xwork2.validator.validators.*;
import com.opensymphony.xwork2.validator.ValidationException;
public class TextCaseValidator extends FieldValidatorSupport
{
public TextCaseValidator() {
}
public void validate(Object obj) throws ValidationException
{
String fName = getFieldName();
Object fValue = getFieldValue(fName, obj);
if((fValue instanceof String) &&
(((String)fValue).length() >0)) {
if(!(Character.isUpperCase(((String)fValue)
.substring(0,1).toCharArray()[0]))) {
addFieldError(fName, obj);
}
}
}
}
|
3. Define the validator.xml file and place this in WEB-INF\classes
folder, the location where struts.xml file is already located.
Content of this file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
<validator name="sampleCaseValidator"
class="sample.TextCaseValidator"/>
</validators>
|
4. Rest of the files should be as that of the earlier example,
Struts2 Validation Example
After constructing this example, one can see following sequence of screen
images as fllows:

---

---

---

---

If you have any questions/difficulty in running this example
please do write to me by commenting on this page, using the
below comment form.
If you like to share your comment/suggestions/feedback relating to this Page,
you can do so by droping us an email at
usingframeworks @ gmail . com
with the subject line mentioning URL for this Page (i.e,
/struts2-own-validator.php) or use this
LINK.
As per this website's privacy policy, we never disclose your email id,
though we shall post your comments/suggestions/feedback with
your name (optional) and date on this Page. If you don't want your
comments/suggestions/feedback to be shared in this Page, please
mention so in your email to us. Thank you very much.....
If anything missed out , please let me know at
techienjoy at yahoo . com