AJAX Validation with JQuery instead of DWR or Prototype

I was trying to create a client side validation using ajax with struts 2. I found this document:

http://struts.apache.org/2.x/docs/ajax-validation.html

In my project I am using jquery instead of prototype or dwr and I'm not using the xhtml or other strut2 2 themes. I am using the simple theme and I realized that the javascripts that come with the framework doesn't work in this context (simple theme and jquery so I created another version of the jsp and javascripts in order to make the validation work in this project. The action class, struts.xml and validator configuration are the same as found on the original link. The only thing that has to be done is create a new version of some javascripts and make some minor changes on the jsp:
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
    <head>
        <title>Validation - Ajax - JQuery</title>
        <!- Don't forget these 2 files!! ->
        <script language="JavaScript" src="${pageContext.request.contextPath}/struts/utils.js" type="text/javascript"></script>
        <script language="JavaScript" src="${pageContext.request.contextPath}/struts/xhtml/validation.js" type="text/javascript"></script>
        
        <!- JQuery instead of Prototype ->
        <script type="text/javascript" src="script/jquery-1.5.1.js"></script>
        <!- Simple theme  ->
        <s:head theme="simple" />
    </head>
<body>

<div id="divErrors">

   <!- You could use this div to show the errors ->
</div>

<!- Form with simple theme ->

<s:form method="post" theme="simple" action="quizAjax" id="form" onsubmit="validate(); return false">
    Name: <s:textfield label="Name" name="name" /><br/>
    Age: <s:textfield label="Age" name="age" /><br/>
    Favorite color:<s:textfield label="Favorite color" name="answer"/><br/>
    <s:submit />
</s:form>

<script type="text/javascript">

   /*This is one of the functions that doesn't work using the simple theme, so I redefined it. This can be changed to

   clear the previous errors, as it does in the commented example cleaning the errors on divErrors. As I am just

  showing the messages with alerts I don't need to clear anything, but the method still need to be redefined, even if it is empty.  */

   StrutsUtils.clearValidationErrors = function(form, errors) {
        //clear the div errors
        //$('#divErrors').empty();
    }
    
    
    /* This method is responsible to show the messages. The original versions works with the xhrml and css-xhtml theme but doesn't work with the simple theme

   , so I override the method with another implementation that shows the messages using alerts. You can change the implementation to show the messages as you want,

   but as the previous method this has to be redefined */
    StrutsUtils.showValidationErrors = function(form, errors) {
    
        if(errors.fieldErrors) {
         for(var fieldName in errors.fieldErrors) {
           for(var i = 0; i < errors.fieldErrors[fieldName].length; i++){alert('Field ->' + fieldName + '\nError -> ' + errors.fieldErrors[fieldName][i]);
           }
         }
        }
    };

   

    /*I changed the original prototype call for the jquery's ajax call */

   function validate() {
       $.ajax({
             type: 'POST',
             cache: false,
             url: '<s:url action="quizAjax"/>',
             data: $("#form").serialize() + '&struts.enableJSONValidation=true&struts.validateOnly=true',
             success: function(data) {},
             error: function(data) {
                postValidation(data);
             }
        });
    
       
    }
    

   /*almost the same code, but using the overridden methods instead of the originals  */

    function postValidation(request) {
       var form = $('#form');
           
       //clear previous validation errors, if any
       StrutsUtils.clearValidationErrors(form);
       
       //get errors from response
       var text = request.responseText;
       var errorsObject = StrutsUtils.getValidationErrors(text);
       
       //show errors, if any
       if(errorsObject.fieldErrors) {
         StrutsUtils.showValidationErrors(form, errorsObject);
      } else {
         //good to go, regular submit
         form.submit();
       }
    }
</script>
}}
I hope this can help someone interested in using jquery instead of prototype to do the ajax validation.

  • No labels

3 Comments

  1. Anonymous

    Is simple theme compulsory? Can't I use ajax or xhtml theme and make this work?

    1. Ajax theme contains Dojo so don't mix two different JS libs. Xhtml should be also good as simple theme.

      1. Anonymous

        Yes. That's true. Actually I am trying to fix http://stackoverflow.com/questions/18684370/struts2-jquery-ajax-and-client-side-validatio-not-working-toghether. Here we are using struts2 and struts2-jquery plugin but client side validation does not work. Could you please give your thoughts on such scenario.