Why is struts validation not working for me?

Eric Wilson picture Eric Wilson · Feb 19, 2010 · Viewed 14.3k times · Source

I'm trying to use Struts validation to check various fields entered by users. If anyone is able to help me see what I lack, I would be extremely grateful. Here's what I have:

I put validation.xml and TestAction-validation.xml in WEB-INF/classes/

Here is validation.xml:

<?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="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
    <validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
    . . .
</validators>

Here is TestAction-validation.xml:

<!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="testInt">
    <field-validator type="int">
      <param name="min">0</param>
      <param name="max">9</param>
      <message>Number not in range</message>
    </field-validator>
  </field>
  <field name="testString">
    <field-validator type="stringlength">
      <param name="minLength">4</param>
      <message>String not long enough.</message>
    </field-validator>
  </field>
</validators>

My struts.xml extends struts-default, and I have a extremely simple action class TestAction which extends ActionSupport and has fields testInt and testString.

From what I've read, this should be sufficient for Struts to check the values entered, but it isn't happening. What am I missing?

Answer

Gladwin Burboz picture Gladwin Burboz · Feb 25, 2010

You have two choices, validate on a per-model basis or per-action. To validate at the Action level, you would simply create a file that takes the name {your action}-validation.xml and place it in the same package as the Action class. To validate at the model level, you would create a similar file that takes the name of the model object then direct your Action validation file to validate per the rules in the model's validation file. (Reference)

Put validation.xml in root of your java source files (default package) and put TestAction-validation.xml in same directory where your TestAction.java file is located. Most IDE's will automatically copy all resources to respective directory where your class file will be generated.

Update:

http://struts.apache.org/2.x/docs/validation.html

How Validators of an Action are Found