Question

I'm rewriting parts of an old project to make use of the struts 1 validator framework.

I've adapted the validation rules on each individual field, with a regular expression that can be reused in other forms, such as:

        <field property="idNumber" depends="mask">
            <msg name="mask" key="error.formating.idnumber" />
            <arg position="0" value="SearchForm.idNumber" />
            <var>
                <var-name>mask</var-name>
                <var-value>${maskIdNumber}</var-value>
            </var>
        </field>

There's one validation left to implement: I need to make sure that the user's has filled any of the fields before submitting. Looking at the FAQ I saw that there are conditions like validwhen that can be used to validate fields against each other, but if I'm not mistaken they have to be attached to one of the form's field.

If I write this:

        <field property="idNumber" depends="validwhen">
            <msg name="mask" key="error.form.empty" />
            <arg position="0" value="SearchForm.idNumber" />
            <var>
                <var-name>test</var-name>
                <var-value>(idNumber != null) or (packageNumber != null)</var-value>

            </var>
        </field>    

The test will only be tried if the field "idNumber" is not empty, right ? The FAQ states that

Any field that isn't 'required' will skip other validations if the field is null or has a length of zero.

Was it helpful?

Solution

I've tried using validwhen, but it was introduced in Stuts 1.2, and I'm on 1.1 so I get the error No ValidatorAction called validwhen found for field idNumber.

I could use requiredif but it may use the worst syntax I have ever seen.

Instead, I followed the technique from https://stackoverflow.com/a/20086863/113305, and used both the Struts validator framework and the validate() method:

    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    ActionErrors errors = super.validate(mapping, request);

    if (idNumber.length() < 1 && packageNumber .length() < 1) {
        errors.add("emptyForm",
                new ActionError("error.form.empty", "emptyForm"));
    }

    return errors;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top