Use validate method and validation xml together in Struts 1

本小妞迷上赌 提交于 2019-12-04 15:31:23

I ran into this same issue ashwinsakthi. Here's how I resolved it.

NOTE: My form bean inherits from ValidatorForm and not ValidatorActionForm like in your code. ValidatorActionForm inherits from ValidatorForm so I think it'll work.

The idea is to call the parent validate method from inside your form. You'll get the errors, if any, from the validator framework first that way. Then you go ahead and add your own validation the normal way.

@Override
public ActionErrors validate(
        ActionMapping mapping,
        HttpServletRequest request) {

    // errors return from validator framework (validation.xml file rules)
    ActionErrors errors = super.validate(mapping, request); 

    // Now check other properties (outside of validation.xml)
    if(somefield == ""  ) {
        errors.add("example", new ActionMessage("some.resource.file.key"));
    }

    ... continue to validate your properties

    return errors;
    }

In my jsp file (where my form is) I include the following for all errors to display after the form is posted:

<font color="red">
<html:errors/>
</font>

Finally here is a snippet from my struts-config.xml file.

   <action 
        path="/hellotest"
        type="com.dan.HelloTestAction"
        name="helloTestForm"
        scope="request"
        input="/index.jsp"
        validate="true">
    <forward name="success" path="/result.jsp"/>
    <forward name="failure" path="/index.jsp"/>
   </action>

In my testing I get the expected results you are expecting. Try it out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!