tags:

views:

1267

answers:

3

I use Struts v1.3 and have following input form:

In struts-config.xml:

    <form-bean name="testForm" 
               type="org.apache.struts.validator.DynaValidatorForm">
        <form-property name="displayName" type="java.lang.String" />
    </form-bean>

In validation.xml:

    <form name="testForm">
        <field property="displayName" depends="required">
            <arg key="input.displayName" />
        </field>
    </form>

How do I trim value of "displayName"? How do I trim values of all "java.lang.String" input fields of the form?

+1  A: 

You may have a chance to trim the string right at the moment, the request processor updates the data from the input fields to the form. This was not tested, but what happens when you modify the setter setDisplayName(String displayName) to something like

public void setDisplayName(String displayName) {
    this.displayName = displayName.trim();
}

This is not a very good solution, because it migrates logic into a setter.

regards

mana
A: 

Alternatively try using javascript regexp in the jsp that will trim onfocus or onblur

< html:text name="testForm" property="displayName" onfocus="javascript:this.value=this.value.replace(/^\s+|\s+$/g,'')" onblur="javascript:this.value=this.value.replace(/^\s+|\s+$/g,'')" />

Krishna
This seems really really verbose and error prone and easy to forget. I agree it works, but trimming in the form setter or even in the action seems better to me.
Randy Stegbauer
A: 

If you don't mind having String manipulation logic in your Form class, you can try the StringUtils methods in Apache's Commons Lang JAR:

StringUtils JavaDoc

This will let you trim your Strings in a number of specific ways, whether you want to trimToEmpty, trimToNull, etc. This means you have access to null-safe methods, which can be useful with some values.

JohnRegner