How to define Custom Validation Rules

by Ombretta Malinverno
4,518 views Published on May 02, 2018
Applies to: 7.2 or higher
Table of contents

Introduction

Validation is used to verify that the data inserted into a form by the user complies with the application domain's requirements. WebRatio Platform includes several predefined types of Validation Rules that cover the most common validation cases. But sometimes, depending on the scope of the Web application, the need to define new validation can emerge.

WebRatio Platform allows you to define a custom validation rule. The validation can be defined for a single field, or form components or multiple form components.

This article explains how to create a custom validation rule and how to use it in your Web Project.

Validation Rule Wizard

Defining a custom validation rule requires a container project. Thus, it is necessary to add a Components Project to your workspace:

  1. Select File > New > Components Project from the main menu.
  2. Give a name to the Components Project.
  3. Press the Finish button.

Let’s add a new Validation Rule:

  1. Select File > New > Validation Rule from the main menu.
  2. Give a name to the validation rule and choose the target Components Project.

  1. Press the Next button.
  2. Choose whether the rule is related to a single field or to the component.
  3. Finally, press the Finish button to confirm the procedure.

The wizard creates different folders inside the Components Project related to the validation rule.

  • Images. In this folder, you can place a 16x16 PNG file to represent the icon for your validation rule. This icon will be used in WebRatio Platform to show your validation in the list of the available ones.
  • Layout. This folder contains the "Bundle.xml" file, which is used to retrieve the default error messages that the component should show to the user when the validation fails.
  • Logic. This folder contains the "Logic.template", in which the user defines the Java class containing the logic of the validation rule and the configuration made by the user through the Properties View.
  • Warnings. This folder contains the "WebModel.template" file that is invoked when the user runs the Find Model Problems command to show warning or errors that are present in the model. The folder and the related file are not created automatically during the wizard procedure, but you can them manually.
  • ValidationRule.xml. This file describes how the validation rule can be configure at design time in the Web Project.

In the next sections, the files presented here will be explained in detail.

ValidationRule.xml

The "ValidationRule.xml" file contains the entire custom validation rule definition and configuration. This file is an editor that contains the validation rule’s specifications in design time when you use it in the model.

The validation rule information is split into four pages:

  • General
  • Sub-Elements
  • Documentation
  • XML

General

This is the first page, composed of two blocks: the General Information of the custom validation like the Name and the Type where it can be inserted.

These are the properties that you can configure:

  • 16x16 Icon. The rendition of the validation rule in the Outline View. You can change the 16x16 icon by inserting a PNG file named "16.png" in the "Images" subfolder of the validation rule configuration folder.
  • Name. The XML tag name given to the validation rule.
  • ID Prefix. The prefix you want the validation rule to be identified by in the Web Project (e.g., "mnd" for the "Mandatory" validation rule).
  • Name Prefix.The default name prefix of the validation rule when it is added to the model.
  • Label. The label used to visualize the validation rule in the "Select Validation Rule" dialog.

You can set the type of the validation rule by changing the selection from "Single field" to "Component".

  • Component Contexts. The property permits the user to define that a validation rule can be applied only to specific components or fields, by simply set a pipe-separated list of component tags or field tags (preceded by component tags) as in the following examples: "MultiChoiceIndexUnit|PowerIndexUnit", "MultiEntryUnit/Field|MultiEntryUnit/SelectionField".

Sub-Elements

In this page, you can configure the properties of the validation rule. These properties will be available in the rule's Properties View once it has been added to an element in the Web Project.

You can edit the options for each validation rule property. The sub-elements have a common property:

  • Label. It defines the label used to visualize the property in the Properties View. If the field label is void, then the sub-element name is used as the label.

Moreover, each sub-element has its own properties. Here is the list of sub-element types.

  • Attribute Property. This property permits the user to select an entity attribute. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the attribute identifier.
    • Entity Id Expr (mandatory). This defines the XPath expression to reach the entity identifier defined in the Entity property. The identifier allows to reach the Domain Model Entity.
    • Include Derived. This defines if the attribute can be a derived attribute.
  • Attributes Property. This property permits the user to select a set of entity attributes. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the space-separated list of attribute Identifiers.
    • Entity Id Expr (mandatory). This defines the XPath expression to reach the entity identifier defined in the "Entity" property. The identifier allows to reach the Domain Model Entity.
    • Include Derived. This defines if the attributes can be derived attributes.
  • Boolean Property. This property holds a true or false value. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the Boolean value.
    • Default Value. The default value of the property. It can be true or false.
  • Database Property. This property permits the user to select a database. The related property of the element is:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the database identifier.
  • Entity Property.This property permits the user to select the entity from which the content of the validation rule is drawn. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the entity identifier.
    • Include Derived. This defines whether the entity from which the content is drawn can be a derived entity.
    • Removable. This defines whether the property can return to a blank value.
  • Enumeration Property. This property permits the user to select one of the proposed values. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the selected value.
    • Default Value. The default value of the property. The value must be one of the values defined as Enumeration Item. The Enumeration Item is its sub-element and defines the possible property values. Its properties are:
      • Value (mandatory). This represents the value that appears in the DOM project.
      • Label. The visualized label representing the value. If the field is empty, then the capitalized value is used (e.g., plain is shown as "Plain").
  • Field Property. This property permits the user to select another field. The related property of the element is:
    • Attribute Name (mandatory). This defines the name of the XML attribute that contains the field identifier.
  • File Property. This property permits the user to select a file that has to be associated to the validation rule. The properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the selected file path.
    • Extension. The file accepted extension.
    • Default Value. The default path of a file.
  • Float Property. This property permits the user to write a float value to associate to the property. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the float value.
    • Default Value. The default float value.
  • Integer Property. This property permits the user to write an integer value to associate to the property. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the integer value.
    • Default Value. The default integer value.
  • List Property. This property permits the user to create and manage a list of element children. The related properties of the element are:
    • Element Name (mandatory). This defines the tag name of the XML element designed to contain each value.
    • Attribute Name (mandatory). This defines the name of the XML attribute that contains the element value.
  • Ordering Property. This property permits the user to order the children of the element. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute that contains the space-separated children identifiers listed in the selected order.
    • Elements Expr (mandatory). This defines the XPath expression used to reach the elements being ordered.
  • Stored Procedure Property. This property permits the user to write a string value to associate with the property. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the procedure's name.
    • Database Id Expr (mandatory). This defines the XPath expression used to reach the database identifier defined in the property. The identifier allows to reach the Domain Model database.
  • String Property. This property permits the user to write a string value to associate with the property. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the string value.
    • Default Value. The default string value.
  • Text Property. This property permits the user to write an arbitrary text or script. The properties of the element are:
    • Element Name (mandatory). This defines the tag name of the XML element designed to contain the text or script.
    • Default Value. The default text or script.
    • Content Type. The type of the text contained in the element. The possible values are "text" and "script".
  • Xsd Provider Property. This property permits the user to select an XSD Provider that has to be associated to the validation rule. The related property of the element is:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the XSD Provider identifier.
  • Xsd Type Property. This property permits the user to select an XSD Type. The related properties of the element are:
    • Attribute Name (mandatory). This defines the name of the XML attribute designed to contain the XSD type identifier.
    • Xsd Provider Id Expr (mandatory). This defines the XPath expression used to reach the XSD Provider identifier defined in the property.
    • Include Elements. This defines whether the XSD type can be of any kind of type.
    • Include Complex Types. This defines if the XSD type can be complex.
    • Include Simple Types. This defines if the XSD type can be a simple.

For each of the properties mentioned above, you can write an Enabled Condition script that defines when the property can be edited in the Properties View.

The script context includes a predefined variable named element that represents the DOM4J validation rule or sub-element. The condition must return true or false value.

For instance the Attributes Property Enabled Condition for the "Like" validation rule is the as follows:

return element["valueField"] == ""

where "element" represents the DOM4J component or sub-component.

Documentation

This page permits the user to briefly describe each sub-element and input parameter. The sub-element documentation consists of a brief description, as you can see in the following image.

XML

This page allows the user to see the XML code of the validation rule.

The Java Class

The Java class is the file containing the business logic of the validation rule. This file is contained in the "src" folder of the Components Project. The "src" folder is visible, under the project, only in the Package Explorer View.

The class is structured through two methods: the constructor and the Validate methods.

Constructor

public ExampleValidationRuleService(String id, RTXManager mgr, Element descr) throws RTXException {

super(id, mgr, descr);

}

In this method, the information is defined that does not change when the validation rule is executed. From this information, it is possible to extract the properties set for the validation rule. These properties are stored in the descriptor file produced by the Logic.template.

For example, to retrieve a string property:

myProperty = DescriptorHelper.getChildValue(descr, "myProperty", false, this);

Validate method

public NextValidationPolicy validate(RTXField field) throws RTXException {

  return NextValidationPolicy.SKIP;

}

This method is called from the Web application when a field with this validation rule has to be processed. This is the point at which the logic of the validation rule has to written. This method returns a value indicating whether the validation of other fields should be considered or not.

The available options are:

  • NextValidationPolicy.SKIP. This option should be used when the validation has to be interrupted. This means that the page will show the user all of the error messages collected until this validation rule is executed.
  • NextValidationPolicy.CONTINUE. This option should be used when the validation has to continue. This means that all of the error messages will be displayed at once on the page once all of the validation rules have been processed.

If you want to register a validation error message that occurred, use the following code:

RTXField.addError(bundleKey).arg("myProperty", myProperty);

where the bundleKey is the key identifying the message within the "Bundle.xml" file of the validation rule. The function ".arg" allows the "myProperty" placeholder present in the "Bundle.xml" file (wrote in this way ${myProperty}) to be replaced with the myProperty variable defined in the Java class that retrieves the value of the validation rule property.

For more information about validation rule APIs, please refer to the "WebRatio Product Documentation" in the Help menu and see the following section: "Web Modeling User Guide" > "Server API - Java" > "com.webratio.rtx.validation".

Example: the "Words Number" validation rule

The proposed example is made up a product creation page, whose form has a text field in which to insert the product description. You want to check that it has no more than 20 words.

Suppose you have the Domain Model containing the "Product" entity.

The IFML model is shown in the following image.

The "Save Product" action definition allows the user to save the product information in the database.

Now, let's create a custom validation rule and the related Components Project to add it. Use the procedure from the "Validation Rule Wizard" section to create them, and name the validation rule "WordsNumber".

Validation Rule.xml

The General Properties are configured as follows:

The validation rule is characterized by a property defining the maximum number of words that a text field can contain. For this purpose, in the Sub-Element page, you need to add the "Words Number" integer property. This element will be shown as a property in the Properties View of the validation.

Write a brief description in the Documentation page that explains the functionality of the validation rule. The descriptions of each element will be shown as tooltips in the Properties View.

Logic.template file

The "Logic.template" file retrieves the properties listed in the Properties View of the validation:

#?delimiters <%,%>,<%=,%>
<%
setXMLOutput()
%>

<Descriptor service="com.webratio.units.custom.WordsNumberValidationRuleService">
  <WordsNumber><%= element["wordsNumber"] %></WordsNumber>
</Descriptor>

where "element" represents the element with this validation rule.

Bundle.xml file

The "Bundle.xml" file contains the message to display if the validation rule fails.

<?xml version="1.0" encoding="UTF-8"?>
<Bundle>
  <Entry key="WordsNumber.error">
    The ${fieldName} exceeds ${wordsNumber} words
  </Entry>
</Bundle>

where ${fieldName} retrieves the name of the field where the validation rule has been added and ${wordsNumber} retrieves the value of the "Words Number" property defined in the Properties View of the validation rule.

Java Class

This is the Java service class of the example:

package com.webratio.units.custom;

import org.dom4j.Element;

import com.webratio.rtx.RTXException;
import com.webratio.rtx.RTXManager;
import com.webratio.rtx.core.BeanHelper;
import com.webratio.rtx.core.DescriptorHelper;
import com.webratio.rtx.validation.AbstractFieldValidationRuleService;
import com.webratio.rtx.validation.NextValidationPolicy;
import com.webratio.rtx.validation.RTXField;

public class WordsNumberValidationRuleService extends AbstractFieldValidationRuleService {

  private final int wordsNumber;

  public WordsNumberValidationRuleService(String id, RTXManager mgr, Element descr) throws RTXException {
    super(id, mgr, descr);
    String value = DescriptorHelper.getChildValue(descr, "WordsNumber", true, this);
    this.wordsNumber = Integer.parseInt(value);
  }

  public NextValidationPolicy validate(RTXField field) throws RTXException {
    String[] words = null;
    String value = BeanHelper.asString(field.getValue());
 
    if (!BeanHelper.isNullOrEmptyString(value)){
      words = value.split(" ");
      if (words.length <= wordsNumber){
        return NextValidationPolicy.CONTINUE;
      } else {
        field.addError(this.getBundleKey()).arg("wordsNumber", wordsNumber);
        return NextValidationPolicy.SKIP;
      }
    } else {
      return NextValidationPolicy.CONTINUE;
    }
  }
}
  • Line 15. The definition of the "wordsNumber" variable used in the code.
  • Lines 19-20. This code retrieves the value set in the  "Words Number" property in the Properties View of the validation rule.
  • Line 24. The definition of an array used to split the string.
  • Line 25. It retrieves the value filled into the field.
  • Lines 27-35. In this part of code the field value is manipulated depending of the "Words Number" property.
  • Line 28. The value is split into single words to count them.
  • Lines 29-31. If it is less or equal to the value of the property, the validation is OK.
  • Lines 31-33. This code manages when the validation fails.
  • Line 32. This code retrieves the error message and replace the "wordsNumber" placeholder with the "wordsNumber" variable defined in the Java class.
  • Lines 35-37. This code manages when the string is empty or null.

You need to add the Component Project in which the validation rule is defined as dependency of your Web Project, to allow it to be added to the field.

  1. Go to the Project tab.
  2. Check the Enable Dependencies property.
  3. Press Yes.
  4. Press the Add... button.
  5. Choose your Components Project.
  6. Press Yes to save and reload the project.

Let's apply the "Words Number" validation rule to the "description" text field:

  1. Right-click on the field.
  2. Select Add > Validation Rule.
  3. Select "Words Number" in the opening dialog.
  4. Press OK to confirm.

Generate and run the Web application page, and test the validation rule.

How to use the sample project

You can use the "WordsNumberValidationRuleSample.zip" and the "sampleCustomComponents.zip" attached files to this article to test the usage of this custom validation rule.

Follow these steps to use the project:

  1. Import the zip files into the WebRatio Platform. You can learn how to do this by watching the "Organize the Workspace" online lesson.
  2. Generate the project with the "Generate and Run on Cloud" command if you have a WebRatio Community Platform version; otherwise, use the "Generate and Run" command.
  3. Visit http://localhost:8080/WordsNumberValidationRuleSample/ or http://freeXXXXX-freeapp.eu.webratio.net/ with any browser.
  4. Fill the product information into the form.
  5. Press the "Save" button to check if the "description" field has more or less than 20 words.