Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Ajax validation with Struts 2

Support for Ajax and JavaScript takes the pain out of Web-form validation

  • Print
  • Feedback

Page 6 of 6

Advanced Ajax validation

As I've mentioned, Struts 2 themes are collections of templates (Freemarker templates) that custom tags use to render HTML. When it comes to validation and forms, all themes try to manage the form's layout. The xhtml and ajax themes use HTML tables, and the css_xhtml theme uses CSS styles. Disappointingly, this fact makes application design unpredictable.

The way Struts 2 suggests to apply custom design to the HTML produced by custom tags is to learn Freemarker and extend or modify the default templates. If you're comfortable with that approach, you can skip the rest of this article.

Why Struts 2 modifies form layouts
Struts 2 themes modify form layout so that the right error labels appear in the right places. For example, the xhtml theme creates an HTML table for a form with a row for each form field, and then uses JavaScript functions to add and remove an extra row dynamically with an error message above the field row. The odds are that not every Web application will follow the table-layout approach for form layout, making the themeless approach a useful alternative.

Unfortunately, for a small- or middle-scale project, when a product is to be delivered within a strict timeframe, learning Freemarker is not an optimal approach. Furthermore, in most applications, different forms have different designs. Fortunately, for client-side validation (both plain and Ajax) you can apply no-theme approach if a well-designed Web form needs to become live quickly.

Let's copy the output produced by a Struts 2 ajax theme template into a separate AdvancedInput.jsp file and apply a custom form layout, as shown in Listing 14:

Listing 14. FirstInput.jsp form: Advanced Ajax validation

 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
   <!--scripts required for validation-->
   <script type="text/javascript" src="struts/validationClient.js"></script>
   <script type="text/javascript" src="dwr/interface/validator.js"></script>
   <script type="text/javascript" src="dwr/engine.js"></script>
   <script type="text/javascript" src="struts/ajax/validation.js"></script>
   <script type="text/javascript" src="struts/xhtml/validation.js"></script>
   <style type="text/css">
      .err {color: red; font-size: 10px;}
      .custom {text-align: center;}
   </style>
</head>
<body><s:actionerror/>
<form id="First_" name="First_" action="First_.action" namespace="/" class="custom">
   Name:<br><input type="text" name="name" id="First__name" onblur="validate(this);"><br>
   Age:<br><input type="text" name="age" id="First__age" onblur="validate(this);"><br>
   Gender (Male/Female):<br><input type="text" name="gender" id="First__gender" onblur="validate(this);"><br>
   <input type="submit" dojoType="struts:Bind" event="onclick" value="Submit" id="First__0">
</form>
</body>
</html>

One of JavaScript's (few) benefits is that you can replace any function with a custom one. So, once you know which function is responsible for rendering the error messages, you can easily replace it with your own -- one that makes error messages appear at the exact position that your designer envisions.

Generally, just two JavaScript functions are responsible for error display in Struts 2 validation: clearErrorMessages(form) and addError(e, errorText). The clearErrorMessages(form) function is called to clear all error labels for a given form. The addError(e, errorText) function is called to put an errorText error label that is related to the HTML e element. Listing 15 adds customized error handling to AdvancedInput.jsp:

Listing 15. FirstInput.jsp form: Added JavaScript

 <script type="text/javascript">
   function addError(e, errorText) {
      var errDiv = document.createElement('div');
      errDiv.setAttribute('errorFor', e.getAttribute('id'));
      errDiv.innerHTML = errorText;
      errDiv.className = 'err';
      e.parentNode.insertBefore(errDiv,e);
   }

   function clearErrorMessages(form) {
      var prevErrDivs = form.getElementsByTagName('div');
      for(var i=0; i<prevErrDivs.length; i++) {
         if(prevErrDivs[i].getAttribute('errorFor')) {
            prevErrDivs[i].parentNode.removeChild(prevErrDivs[i]);
            i--; // prevErrDivs colection changes as elements removed
         }
      }
   }
</script>

Now the free-style designed form is live with Ajax validation.

In conclusion

In this article you've learned how to do both server-and client-side validation with Struts 2 -- and how to combine the two for advanced Ajax applications. Struts 2 isn't the only Java Web application framework to offer a validation framework, but it's the one that goes beyond Java to provide integrated support for plain JavaScript and advanced Ajax validation. Its out-of-the-box validators and custom-validator support are a welcome salve for validation pain.

About the author

Oleg Mikheev is a Sun Certified Java Developer and IBM WebSphere Portal Developer with 10 years of experience with Java technologies. Oleg is currently employed as systems analyst by Gemini Systems, and is a postgraduate student at St.-Petersburg State Polytechnical University, Russia.

Read more about Enterprise Java in JavaWorld's Enterprise Java section.

  • Print
  • Feedback

Resources

More