Struts 2 > Form validation |

Struts 2
Form validation
Edit Page Browse Space Add Page Add News
Added by botah, last edited by Ted Husted on Sep 02, 2006 (view change)

Asynchronous Client side form validation in WW2.2 is super easy, and super cool.

Here is what I learned while getting it running.

1) Have WW Validation working already. Go for it, use something cool like a nested validator with a email validation rule.
2) You need the latest DWR jar in WEB-INF/lib.
3) Add this code to your web.xml

web.xml

    <servlet>
            <servlet-name>dwr</servlet-name>
            <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
        </servlet>

        <servlet-mapping>
            <servlet-name>dwr</servlet-name>
            <url-pattern>/dwr/*</url-pattern>
        </servlet-mapping>

4) Update an existing form. Depending on how extensively you used WW form controls this step might take a few moments. The controls all need to be generated via WW tags. No being lazy and just using <form name="xxx". Ill explain why this is in a moment. You will need to follow these rules to stay on the happy path:

- <ww:form must have an id element.
- Again use only ww: tags
- To turn client side validation on, set the validate="true" attribute
- Well I guess thats it.
  Here is a sample form:

      <ww:form id="input_form" action="'SaveUser.action'" method="post" validate="true">
                  <ww:textfield label="'First Name'" name="'bo.firstName'" size="20" required="true"/>
                  <ww:textfield label="'Last Name'" name="'bo.lastName'" size="20" required="true"/>
                  <ww:textfield label="'Email'" name="'bo.emailAddress'" size="20" required="true"/>
                  <ww:submit name="'submit'" value="'Save'" cssClass="'primary'"/>
              </ww:form>

  See what WW generates for you. This is why its critical to use all the WW tags. There are two things happening here. In the ww:form tag ww includes all the JavaScript libs. And secondly, notice how the ids for all the child elements got filled in based on the name of the parent form? Thats the second half of the magic. WWs JavaScript uses these ids to getElementById.

Generated Code

    <script src="/agility/webwork/validationClient.js"></script>
    <script src="/agility/dwr/interface/validator.js"></script>
    <script src="/agility/dwr/engine.js"></script>
    <script src="/agility/webwork/template/xhtml/validation.js"></script>
    <form namespace="" id="input_form" name="SubmitUser" action="/agility/SubmitUser.action">

    <p>
    <label for="input_form_bo.firstName" class="label"><span class="required">*</span>First Name:</label>
    <input name="bo.firstName" size="20" value="admin" id="input_form_bo.firstName" onblur="validate(this);" type="text">
    </p>
    <input type="submit" name="submit" value="Save" class="primary"/>
    </form>
    <p>

5) Thats about it. You should be off to the races using asynchronous client side validation!!!