Commits

Anonymous committed 3e0f167

javascript-based client side validation

git-svn-id: http://svn.opensymphony.com/svn/webwork/trunk@368573baa09-0c28-0410-bef9-dab3c582ae83

Comments (0)

Files changed (13)

src/etc/example/xwork.xml

             <result name="error">validationForm.vm</result>
         </action>
 
+        <action name="javascriptValidation" class="com.opensymphony.webwork.example.JavascriptValidationAction">
+            <interceptor-ref name="validationWorkflowStack"/>
+            <result name="success" type="redirect">http://www.opensymphony.com</result>
+            <result name="input">javascript-input.jsp</result>
+        </action>
+
 		 <!-- JasperReport Basic Test Actions -->
         <action name="jasperTest" class="com.opensymphony.webwork.example.jasperreports.OrderListAction">
             <param name="dataSource">orders</param>

src/etc/taglib.tld

             <required>false</required>
             <rtexprvalue>true</rtexprvalue>
         </attribute>
+        <attribute>
+            <name>validate</name>
+            <required>false</required>
+            <rtexprvalue>true</rtexprvalue>
+        </attribute>
     </tag>
 
     <tag>

src/example/com/opensymphony/webwork/example/JavascriptValidationAction-validation.xml

+<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.dtd">
+<validators>
+    <field name="test">
+        <field-validator type="requiredstring">
+            <message>You must enter a string.</message>
+        </field-validator>
+    </field>
+</validators>

src/example/com/opensymphony/webwork/example/JavascriptValidationAction.java

+package com.opensymphony.webwork.example;
+
+import webwork.action.ActionSupport;
+
+public class JavascriptValidationAction extends ActionSupport {
+    String test;
+
+    public String execute() throws Exception {
+        System.out.println("You entered: " + test);
+        return SUCCESS;
+    }
+
+    public String getTest() {
+        return test;
+    }
+
+    public void setTest(String test) {
+        this.test = test;
+    }
+}

src/example/validators.xml

 <validators>
     <validator name="required" class="com.opensymphony.xwork.validator.validators.RequiredFieldValidator"/>
-    <validator name="requiredstring" class="com.opensymphony.xwork.validator.validators.RequiredStringValidator"/>
+    <validator name="requiredstring" class="com.opensymphony.webwork.validators.JavaScriptRequiredStringValidator"/>
     <validator name="int" class="com.opensymphony.xwork.validator.validators.IntRangeFieldValidator"/>
     <validator name="date" class="com.opensymphony.xwork.validator.validators.DateRangeFieldValidator"/>
     <validator name="expression" class="com.opensymphony.xwork.validator.validators.ExpressionValidator"/>

src/java/com/opensymphony/webwork/validators/JavaScriptRequiredStringValidator.java

+package com.opensymphony.webwork.validators;
+
+import com.opensymphony.xwork.validator.validators.RequiredStringValidator;
+
+import java.util.Map;
+
+public class JavaScriptRequiredStringValidator extends RequiredStringValidator implements ScriptValidationAware {
+    public String validationScript(Map parameters) {
+        String field = (String) parameters.get("name");
+        StringBuffer js = new StringBuffer();
+
+        js.append("value = form.elements['" + field + "'].value;\n");
+        js.append("if (value == \"\") {\n");
+        js.append("\talert('" + getMessage(null) + "');\n");
+        js.append("\treturn false;\n");
+        js.append("}\n");
+        js.append("\n");
+
+        return js.toString();
+    }
+}

src/java/com/opensymphony/webwork/validators/ScriptValidationAware.java

+package com.opensymphony.webwork.validators;
+
+import java.util.Map;
+
+public interface ScriptValidationAware {
+    public String validationScript(Map parameters);
+}

src/java/com/opensymphony/webwork/views/jsp/ui/AbstractUITag.java

 import com.opensymphony.webwork.views.velocity.VelocityManager;
 
 import com.opensymphony.xwork.util.OgnlValueStack;
+import com.opensymphony.xwork.validator.ActionValidatorManager;
+import com.opensymphony.xwork.validator.Validator;
+import com.opensymphony.xwork.validator.FieldValidator;
+import com.opensymphony.xwork.Action;
+import com.opensymphony.xwork.ActionContext;
+import com.opensymphony.xwork.ActionInvocation;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
 import java.io.Writer;
 
-import java.util.Enumeration;
-import java.util.Properties;
+import java.util.*;
 
 import javax.servlet.ServletConfig;
 import javax.servlet.ServletContext;
             addParameter("id", getId());
         }
 
+        // now let's do some JavaScript stuff. or something
+        if (tag != null) {
+            ActionInvocation ai = (ActionInvocation) stack.getContext().get(ActionContext.ACTION_INVOCATION);
+            Action action = ai.getAction();
+            String actionName = ai.getProxy().getActionName();
+            List validators = ActionValidatorManager.getValidators(action.getClass(), actionName);
+            for (Iterator iterator = validators.iterator(); iterator.hasNext();) {
+                Validator validator = (Validator) iterator.next();
+                if (validator instanceof FieldValidator)
+                {
+                    FieldValidator fieldValidator = (FieldValidator) validator;
+                    if (fieldValidator.getFieldName().equals(name)) {
+                        tag.registerValidator(name, fieldValidator, new HashMap(getParameters()));
+                    }
+                }
+            }
+        }
+
         evaluateExtraParams(stack);
     }
 

src/java/com/opensymphony/webwork/views/jsp/ui/FormTag.java

 package com.opensymphony.webwork.views.jsp.ui;
 
 import com.opensymphony.webwork.ServletActionContext;
+import com.opensymphony.webwork.validators.ScriptValidationAware;
 import com.opensymphony.webwork.views.util.UrlHelper;
 
 import com.opensymphony.xwork.ActionContext;
+import com.opensymphony.xwork.validator.FieldValidator;
 import com.opensymphony.xwork.util.OgnlValueStack;
 
 import org.apache.velocity.Template;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.Writer;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Iterator;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
     String actionAttr;
     String enctypeAttr;
     String methodAttr;
+    String validateAttr;
+    Map fieldValidators;
+    Map fieldParameters;
 
     //~ Methods ////////////////////////////////////////////////////////////////
 
         this.methodAttr = method;
     }
 
+    public void setValidate(String validate) {
+        this.validateAttr = validate;
+    }
+
     public void evaluateExtraParams(OgnlValueStack stack) {
         super.evaluateExtraParams(stack);
 
         if (methodAttr != null) {
             addParameter("method", findValue(methodAttr, String.class));
         }
+
+        if (validateAttr != null) {
+            addParameter("validate", findValue(validateAttr, Boolean.class));
+        }
+
+        if (fieldValidators != null) {
+            StringBuffer js = new StringBuffer();
+            js.append("form = document.forms['" + getParameters().get("name") + "'];\n");
+            for (Iterator iterator = fieldValidators.entrySet().iterator(); iterator.hasNext();) {
+                Map.Entry entry = (Map.Entry) iterator.next();
+                if (entry.getValue() instanceof ScriptValidationAware) {
+                    ScriptValidationAware jsa = (ScriptValidationAware) entry.getValue();
+                    Map params = (Map) fieldParameters.get(entry.getKey());
+                    js.append(jsa.validationScript(params));
+                    js.append('\n');
+                }
+            }
+
+            addParameter("javascriptValidation", js.toString());
+        }
     }
 
     protected String getDefaultTemplate() {
         return TEMPLATE;
     }
+
+    public void registerValidator(Object name, FieldValidator fieldValidator, Map params) {
+        if (fieldValidators == null) {
+            fieldValidators = new HashMap();
+        }
+
+        if (fieldParameters == null) {
+            fieldParameters = new HashMap();
+        }
+
+        fieldValidators.put(name, fieldValidator);
+        fieldParameters.put(name, params);
+    }
+
+    public Map getFieldValidators() {
+        return fieldValidators;
+    }
+
+    public Map getFieldParameters() {
+        return fieldParameters;
+    }
 }

src/java/template/xhtml/form-close.vm

+#if ($parameters.validate)
+    <script>
+    function ${parameters.name}_validate() {
+        $parameters.javascriptValidation
+        return true;
+    }
+    </script>
+#end
 </form>
 </table>

src/java/template/xhtml/form.vm

     #if ($parameters.action)    action="$!webwork.htmlEncode($parameters.action)"   #end
     #if ($parameters.method)    method="$!webwork.htmlEncode($parameters.method)"   #end
     #if ($parameters.enctype)   enctype="$!webwork.htmlEncode($parameters.enctype)" #end
+    #if ($parameters.validate)  onsubmit="return(${parameters.name}_validate())"    #end
 >

src/webapp/default.jsp

     <li><a href="expressionValidation.action">Visitor validation example</a>
         with expression validation
     </li>
+
+    <li><a href="javascriptValidation.action">Validation that uses JavaScript to do client side support</a></li>
 </ul>
 
 

src/webapp/javascript-input.jsp

+<%@ taglib uri="webwork" prefix="ww" %>
+
+<html>
+    <head>
+        <title>JavaScript Validation Input</title>
+    </head>
+    
+    <body>
+        <ww:form name="'test'" action="javascript" validate="true" >
+            <ww:textfield label="'Can't be empty'" name="'test'" required="true"/>
+            <ww:submit value="'Submit'"/>
+        </ww:form>
+    </body>
+</html>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.