How to Validate Form Fields

Extensibility
Extensibility covers the mechanisms by which you, as the user or developer, can extend the functionality of the Teradata Database, for example with the use of User Defined Functions, or UDFs.
Teradata Employee

How to Validate Form Fields

This section describes how to add unified client-server validation to JSP pages using the Teradata Viewpoint Client Validation Framework (CVF). The CVF allows users to quickly add validation to their forms and provides a common error message style. The necessary resources include:

  • jQuery and jQuery validator
  • TjsValidator - Teradata Viewpoint validation extensions
  • Spring MVC - Preferably by using SimpleFormController, but other controllers can be supported as well

The CVF can be used on forms that require input field validation. Some fields may be validated by JavaScript on the client side (e.g., empty or ill-formed field) while other fields might require validation on the server side (e.g., user name already exists).

The examples below use Spring Form Tags for the input fields. If you are unfamiliar with Spring Form Tags, read How to Use Spring Form Tags first.

Client-Side Validation

Adding client-side validation allows for quick processing of basic validation rules without the expense of submitting an entire form to the server. Forms should not be submitted to the server if there are errors such as missing input values, out-of-range values, or invalid value types. The following steps outline the process of adding client-side validation to a form using the Teradata Viewpoint CVF.

For a list of available validation rules included in the TjsValidator library, see the Javascript Library page.

Add the required JavaScript libraries and CSS

This should be done near the top of the main JSP file for a portlet. The following files are required and can be found in the Teradata Viewpoint CommonsWeb project.

<script type="text/javascript" src="/CommonsWeb/js/TjsValidator.js" ></script>
<script type="text/javascript" src="/CommonsWeb/js/TjsBackground.js" ></script>
<script type="text/javascript" src="/CommonsWeb/js/jquery.js" ></script>
<script type="text/javascript" src="/CommonsWeb/js/jquery.form.js" ></script>
<script type="text/javascript" src="/CommonsWeb/js/jquery.tabs.js" ></script>
<script type="text/javascript" src="/CommonsWeb/js/jquery.validate.js" ></script>
<script type="text/javascript" src="/CommonsWeb/js/jquery.dimensions.js" ></script>
<script type="text/javascript" src="/CommonsWeb/js/jquery.metadata.js" ></script>

<link rel="stylesheet" type="text/css" href="/CommonsWeb/css/global.css" />

Add validation markers to your fields

Validation metadata is added as part of the field css class.

<form:input path="foo" cssClass="inputValidate{required:true, placement:TjsValidator.LEFT" />
  •  Provide NAME and ID attributes (these should match).
  • Add inputValidate as an inline option to the CLASS attribute. If you have any existing class definitions, simply place inputValidate after a space (as shown).
  • The brackets are required and the rules should be separated by commas. To use a rule, the rule name is followed by a colon and the rule arguments. In this example, the rule named 'required' has an argument of true.
  • The 'placement' rule is not required and defaults to TjsValidator.RIGHT, in which case any validation message appears on the right side of the field being validated.
  • The following placements are supported:
    • RIGHT - The message appears on the right side of the validated field.
    • LEFT - The message appears on the left side of the validated field.
    • TOP - The message appears above the validated field.
    • BOTTOM - The message appears below the validated field.

Add the validator initialization

The following code should be placed in the portlet's onLoad section, which is run once the portlet has finished loading. If you are using the Teradata Viewpoint TDPortalManager, use the onPortletReady method.

<script type="text/javascript">
TDPortalManager.onPortletReady('${context}', function() {
// Add validation to the form fields
var options =
{
context: '${context}',
submitBtn: 'submitBtn'
};
TjsValidator.addValidation("${context}preferenceForm", options);
});
</script>

The context should always be provided. The following options are supported:

  • (String) context - The unique portlet instance id.
  • (String) submitBtn - The id of the OK/Submit/Apply button on the form. This is used to disable the button when there is a validation error.
  • (String) tabContainer - The id of the element containing the jQuery tabs. This is used to disable the tabs when there is a validation error.
  • (function) beforeErrorDisplay - A callback function that is called before an error message is displayed next to an invalid field.
  • (function) postValidation - A callback function that is executed each time after validation has occurred.
  • (boolean) enableServerValidation - A boolean value to indicate to check for server validation errors. True indicates that the framework should check for server validation errors, false indicates that no check should be made.

Add custom validation methods (optional)

It is possible to add custom rules specific to a portlet if none of the CVF validation rules match your needs. Use the following template by placing it within the TDPortalManager onPortletLoad method. It can be added, but is not required, immediately after the call to the TjsValidator addValidation method.

TjsValidator.addMethod (
"checkSomething",
function(value, element, param)
{
// check if the field (element) value is valid
var isValid = blah();
// return true if the field is valid, false otherwise
return isValid;
},
"This is displayed when the field is invalid"
);

Now you can validate your input in a similar manner to the standard validation by specifying the validation name in the class:

<form:input path="foo" cssClass="urlInput inputValidate{checkSomething:'something'}" />

Server-Side Validation

Although many input fields can be validated using client-side rules, there are some cases that require server-side validation. The Jakarta commons-validator library provides common validation routines that can be used for server-side validation. The following steps outline the process of adding server-side validation to a form using the Teradata Viewpoint CVF and Spring Framework validator.

Add validation to your portlet

It is recommended that you use Spring controllers that accept Validators as parameters. These include descendants of BaseCommandController:

  • AbstractFormController
    • SimpleFormController
    • AbstractWizardFormController
  • AbstractCommandController

Generally, all of these include setValidator(Validator) and setValidators(Validator[]), which allow you to easily add one or more validators to your existing code. For more details on how to setup validators, see Spring documentation.

Add the required dependencies

Add the following libraries as dependencies in the portlet's ivy.xml file

<dependency org="springframework" name="spring-modules" rev="0.8" conf="runtime->default" />
<dependency org="apache" name="commons-validator" rev="1.3.1" conf="runtime->default" />
<dependency org="apache" name="commons-collections" rev="3.2" conf="runtime->default" />
<dependency org="apache" name="commons-beanutils" rev="1.6" conf="runtime->default" />
<dependency org="apache" name="commons-digester" rev="1.8" conf="runtime->default" />
<dependency org="antlr" name="antlr" rev="2.7.4" conf="runtime->default" />

Add bean definitions

The following bean definitions should be added to the portlet's Spring context file:

Define the validation-related beans: 

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>

<bean id="validatorFactory" class="org.springmodules.validation.commons.DefaultValidatorFactory">
<property name="validationConfigLocations">
<list>
<value>/WEB-INF/validation-rules.xml</value>
<value>/WEB-INF/validation.xml</value>
</list>
</property>
</bean>

<bean id="beanValidator" class="org.springmodules.validation.commons.DefaultBeanValidator">
<property name="validatorFactory" ref="validatorFactory"/>
</bean>

Add the validator property to your controller:

<bean id="externalContentPreferencesController" 
class="com.teradata.portlets.externalcontent.controllers.ExternalContentPreferencesController">
<property name="contentManager" ref="contentManager"/>
<property name="validator">
<ref bean="beanValidator"/>
</property>
</bean>

Add configuration files

Commons-validator uses XML configuration files that are usually in the same location as Spring configuration files in WEB-INF. You can use a single validator.xml, but the convention is to use two configuration files and a messages properties file:

  • Validation.xml - To provide validator(s) definition
  • Validation-rules.xml - To provide validation routines
  • Messages.properties - Error messages definitions. This is Spring's general way of dealing with external messages. This file unlike XML configuration should go into src/resources directory in your project so when deployed it ends up in WEB-INF/classes.
  • The location of these files is set as property in your ValidatorFactory bean definition (see bean definitions code sample)

Example of validation.xml 

<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1.dtd">
<form-validation>
<formset>
<form name="externalContentPreferences">
<field property="url" depends="required,url">
<arg0 key="external.url"/>
</field>
</form>
</formset>
</form-validation>
  • The form name should match the NAME attribute of the form in the JSP.
  • The field property should match the name of the input field being validated.
  • The arg0 tag specifies the key from messages.properties to use as an argument when there is an error with the field. In this case, the external.url string defined in messages.properties is used as an argument to the errors.required and errors.malformed strings, also defined in messages.properties. See the contents of messages.properties below.

 Example of validation-rules.xml: 

<!DOCTYPE form-validation PUBLIC
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN"
"http://jakarta.apache.org/commons/dtds/validator_1_1.dtd">
<form-validation>
<global>
<validator name="required" classname="org.springmodules.validation.commons.FieldChecks"
method="validateRequired"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.springframework.validation.Errors"
msg="errors.required">
</validator>
</global>
</form-validation>

Example of messages.properties:

### Default messages for External content portlet
external.url=URL
errors.required={0} field is required
errors.malformed={0} format is not valid

Changes to Portlet JSP

Teradata Viewpoint portlet preferences are edited within a pop-up modal dialog based on jQuery Modal plugin. Adding server-side validation to modal pop-up dialogs requires some additional steps, described below.

  • Put the modal dialog into an "updatable" state to prevent automatic dismissal of modal dialog after "Submit" button is clicked. This is done by adding class="modalupdate" attribute to a hidden form field in the modal dialog JSP: 

  • <input type="hidden" name="modal" class="modalupdate" value="<portlet:namespace />" />
  •  In order to display server-side validation errors, the Spring form:errors tag needs to be added for fields that will be validated on the server side, as shown below. Note that the id for the form:errors tag is the id of the field being validated with '-error' appended at the end. This is required. The 'path' attribute should match the 'path' attribute used in the field. 

  • <div class="urlSection">
    <span class="urlName">URL:</span>
    <label> <form:input id="url" path="url" cssClass="urlInput inputValidate {required:true,placement:TjsValidator.RIGHT}" />
    </label>
    <form:errors id="url-error" cssClass="validationError" cssStyle="display:none" path="url" />
    </div>

Important Conventions

When setting up these files, make sure that:

  • Your client HTML form has the NAME attribute set and matches the <form name=""/> attribute in validation.xml
  • In validation.xml, the <field property="url"/> must match HTML form input path set by <form:input path="url"/> or <input name="url" />, which in turn maps to the field in your command object.
Tags (3)