Dashboard > Spring Modules > Using Valang validator > Using your Valang rules to generate client side JavaScript
  Spring Modules Log In View a printable version of the current page.  
  Using your Valang rules to generate client side JavaScript
Added by Oliver Hutchison, last edited by Uri Boness on Jun 06, 2006  (view change)
Labels: 
(None)

The Valang to JavaScript conversion service is a simple extension to the Valang validator package that allows you to use the same Valang validation rules for client-side JavaScript validation that you are already using for your server-side controller validation.

The default JavaScript validator will be activated when the user tries to submit the form being validated and any errors detected by the validator will be presented in an alert box, but if you wish, you may customize any aspect of the validator to suit you needs.

Warning

Prior to release 0.4, there were 2 classes in CVS that allow you to define your Valang validation rules:

1) ValangValidatorFactoryBean which is described in the guide Using Valang validator
2) the new class ValangValidator which can be used by simply changing the class name for your validator bean from ValangValidatorFactoryBean to ValangValidator

To use this JavaScript translation functionality you must be defining your validator using option 2; using option 1 will result in an exception being thrown by the custom tag.

In 0.4 release ValangValidatorFactoryBean was deprecated and is planned to be removed in 0.5.

Moreover, in 0.4 the following package names were changed (in the following order):

org.springmodules.validation.valang -> org.springmodules.validation.parser
org.springmodules.validation -> org.springmodules.validation.valang

Note that this guide still refers to the old package names, so when using 0.4 please remember to conver the examples.

 

Getting Started

Spring MVC

This Getting Started guide assumes that you are using Valang as the Validator implementation for your Spring MVC controllers and using JSP for your views.

If you don't know how to use Valang please read the guide Using Valang validator before you continue with this document.

There are 5 simple steps that are needed to enable the Valang to JavaScript translation:

Step 1 - Add the Valang rules exporter to your DispatcherServlet configuration

Because the translation of your validation rules happens in a custom tag it is necessary for any Valang validation rules used in your controller to be exported into the JSP page context. A convenient Spring MVC interceptor is provided that will automatically export the Valang validation rules for any controllers that make use of them.

If you are using the default handler mapping provided by the DispatcherServlet you will need to add the following to your dispatcher config file:

<bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
    <property name="interceptors">
        <list>
            <bean class="org.springmodules.validation.javascript.taglib.ValangRulesExportInterceptor" />
        </list>
    </property>
</bean>

or, if you have already configured an alternative handler mapping, all you need to do is include the additional ValangRulesExportInterceptor in the list of interceptors used by your custom handler mapping:

<bean id="myHandlerMapping" class="org.springframework.web.servlet.handler.?">
    ...
    <property name="interceptors">
        <list>
            ...
            <bean class="org.springmodules.validation.javascript.taglib.ValangRulesExportInterceptor" />
        </list>
    </property>
</bean>

Step 2 - Configure the Valang custom tag library.

Copy the file valang.tld from the Spring Modules sandbox/src/org/springmodules/validation/javascript/taglib/ directory into the WEB-INF/tlds directory of your web application.

Step 3 - Make the ValangValidator JavaScript code base available

Copy the file valang_codebase.js from the Spring Modules sandbox/src/org/springmodules/validation/javascript/ directory into a directory in your web application where you normally keep downloadable JavaScript source files. e.g. /include/js/.

Step 4 - Import the Valang custom tag and JavaScript codebase into your JSP view

In the JSP file that is used to render the view the form you wish to validate you will need to import the Valang custom tag library by including the following line at the top of the file:

<%@taglib uri="/WEB-INF/tlds/valang.tld" prefix="vl" %>

then somewhere in the HTML <head> section of your JSP template include the JavaScript codebase that you previously saved to your web application (make sure the src attribute matches the directory you used in Step 3):

<html>
<head>
...
<script type="text/javascript" src="/include/js/valang_codebase.js"></script>
...
</head>
...
Handy Hint

If you have a common header that is included in all your JSP views you may want to include the 2 lines shown above in that file so that all of your views will automatically have these lines included.

Step 5 - Use the <vl:validate> tag to generate the JavaScript validator

Inside the HTML for the form element you wish to validate use the <vl:validate> tag to generate the JavaScript validator (the commandName attribute should match the command name of the controller which exported the validation rules in Step 1):

<form method="post">
<vl:validate commandName="command" />
...
</form>

or if you have some validation rules you would like to have applied in addition to the rules that were exported in Step 1 you may include these in the body of the <vl:validate> tag:

<form method="post">
<vl:validate commandName="command">
{ firstName : length(?) < 30 : 'This rule only gets evaluated in JavaScript' }
</vl:validate>
...
</form>

NOTE: The <vl:validate> tag must be inside the <form></form> tags for the form you wish to have the validation apply. If you do not do this the JavaScript validator will be unable to locate the form it is expected to validate and a JavaScript exception will be thrown.

Done

If everything has gone to plan you should now have JavaScript validation.

Reference

Custom Validation Functions

When the Valang to JavaScript translator encounters a custom validation function it generates a call to a JavaScript function with the same name as the Java class of the custom function. e.g. if your validation rule uses a custom validation function whose class is my.custom.validators.IsEmailFunction then the translated JavaScript validation call will be to a function ValangValidator.Rules.prototype.IsEmailFunction().

It is therefore necessary that you provide a JavaScript implementation for the function call generated by the JavaScript translator which is as simple as adding a new function to the ValangValidator.Rules.prototype object defined in the file valang_codebase.js So for example - the IsEmailFunction described above would need the following JavaScript function to be defined at the end of the valang_codebase.js file:

ValangValidator.Rule.prototype.IsEmailFunction = function(value) {
    // very simple email validation
    return value && value.indexOf(".") > 2 && value.indexOf("@") > 0
}

Customizing the Validation feedback

If you wish to customize the validation feedback that is provided by the JavaScript Valang validator you will need to override the function ValangValidator.prototype.showValidationFeedback. This function, which is only called when a validation error has been detected, takes one argument which is an array containing all of the failed validation rules.

It is recommended that you look at the existing implementation as a guide to how the validator handles feedback.

Localization

The current implementation supports localized error messages as long as they do not use any arguments. Messages that take arguments will currently be ignored and only the default error message will be used.

Trouble Shooting

If the validator is not working the first thing you should do is have a look at the JavaScript console; there is likely to be an error message showing there.

For more detail of what the JavaScript Valang validator doing you can enable the extensive logging functionality. To enable the log output all you need to do is include the following HTML (it is recommended that this be placed at the end of the page):

<div id="valangLogDiv"></div>

Once you reload the page the JavaScript Valang validator will detect and output logging information into this div.

Site running on a free Atlassian Confluence Open Source Project License granted to Spring Framework. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.5 Build:#811 Jul 25, 2007) - Bug/feature request - Contact Administrators