Business Rules

  Validators and Converters

Table of Contents
Business RulesPrint||
Validators and Converters

A common requirement in web applications is to perform validation and conversion of field values whenever a user inserts or updates a record, or changes a field value. Code On Time web applications allow the creation of business rules of any complexity using JavaScript, SQL, or C#/Visual Basic. To help get you started, the Project Designer can set up a simple generic validator or converter. The validators and converters have a consistent implementation model.

Validator

Start the Project Designer. In the Project Explorer, switch to the Controllers tab. Right-click on Orders / Fields / OrderDate field node. The context menu will display commands to create a Validator or Converter using JavaScript, SQL, or Code (C#/Visual Basic).

Select Add SQL Validator option.

Add SQL Validator context menu option for a field in the Project Explorer in Code On Time web application generator.

Press OK to confirm creation of the business rule.

Confirmation window to add an SQL business rule.

A validation SQL business rule will be configured to prevent saving of blank values in OrderDate field.

New SQL business rule added to Orders controller.

The script for the sample SQL business rule goes as follows:

if @OrderDate is null
begin
    /* prevent the default action processing */
    set @BusinessRules_PreventDefault = 1
    /* set the focus on the field and display an error */
    set @Result_Focus = 'OrderDate,Required field.'
end

On the Project Browser toolbar, press Browse button and wait for the web application to load.

Navigate to the Orders page, and edit an order. Clear the OrderDate field, and press OK to save. The business rule will validate the Order Date and show a message showing that the field is required.

Order Date field validated and message has appeared declaring that the field is required.

Note that this is a generic validation example. A simpler method to insure that the field is not blank is to mark it as required. Use a business rule when a more complex validation is needed.

Custom Validator

Let’s modify the sample business rule in order to perform a more complex validation. In the Project Explorer, right-click on Orders / Fields / Freight data field node. Select Add SQL Validator.

Add SQL Validator context menu option for a field in Orders controller.

The Project Browser will open the new business rule. Replace the sample script with the following:

if (@Freight is null) or 
    not(@Freight >= 5 and @Freight <= 30)
begin
    /* prevent the default action processing */
    set @BusinessRules_PreventDefault = 1
    /* set the focus on the field and display an error */
    set @Result_Focus = 'Freight,The range is between 5 and 30.'
end

Press OK to save the business rule. On the toolbar, press Browse.

Navigate to the Orders page, and create a new order. If you press OK without entering any values, the first validator on Order Date will display a “Required field.” message.

Error message displayed for validated field when new order is saved.

Enter a value in Order Date. In the Freight field, type “4”, and press OK to save. A message will be displayed, warning the user that the value must be between 5 and 30.

Error message displayed if Freight is not validated in the correct range.

Enter a value in the specified range. When you press OK, the validation test will pass and the record will be saved.

New order saved when Freight value is in the correct range.

Converter

Switch back to the Designer. Right-click on Customers / Fields / City field node. Select Add JavaScript Converter option.

Add JavaScript Converter context menu option for City field in Customers controller.

Press Yes to confirm the addition.

Confirm the creation of a JavaScript converter.

The field will automatically be configured as a calculated field. A business rule will be added that will convert the field value to uppercase when a user inserts, updates, or switches focus from the field.

City_Converter business rule added for Customers controller.

The preconfigured business rule script will look as follows:

var fieldValue = [City];
var commandName = this.arguments().CommandName
var triggerFieldName = this.arguments().Trigger;
var tryConversion = commandName != 'Calculate' ||
    triggerFieldName == 'City';
if (fieldValue != null && tryConversion) {
    // make sure that the value is a string
    fieldValue = fieldValue.toString();
    // convert the value to an upper-case string
    var newFieldValue = fieldValue.toUpperCase();
    // assign a new value to the field
    [City] = newFieldValue;
    // prevent the server-side processing of the event
    if (commandName == 'Calculate')
        this.preventDefault();
}

On the toolbar, press Browse.

Navigate to the Customers page, and create a new record. Type a value in the City data field.

Lowercase text entered into City field.

Press Tab on your keyboard, or use the mouse to shift focus. The value entered in City will be converted to uppercase.

Upon exiting the City field, the JavaScript business rule converts the field value to uppercase.

The major benefit of implementing converters in JavaScript is that the script is executed by the web browser and requires no server interaction.

Custom Converter

Let’s customize the standard converter to perform a more advanced operation – conversion of phone numbers.

In the Project Explorer, right-click on Employees / Fields / HomePhone field node, and select Add JavaScript Converter.

Add JavaScript Converter context menu option for HomePhone field in the Project Explorer.

The business rule will open in the Project Browser. Replace the default business rule script with the following:

var fieldValue = [HomePhone];
var commandName = this.arguments().CommandName
var triggerFieldName = this.arguments().Trigger;
var tryConversion = commandName != 'Calculate' ||
    triggerFieldName == 'HomePhone';
if (fieldValue != null && tryConversion && fieldValue.match(/^\d{10}$/)) {
    var newFieldValue = fieldValue.replace(/(\d{3})(\d{3})(\d{4})/, '($1)-$2-$3');
    [HomePhone] = newFieldValue;
    // prevent the server-side processing of the event
    if (commandName == 'Calculate')
        this.preventDefault();
}

Press OK to save the business rule. On the toolbar, press Browse.

Navigate to the Employees page. Create a new employee, and type in 10 digits in the Home Phone field.

10 Digits entered into Home Phone field.

Shift focus away from the field by pressing Tab or clicking on another area of the page. The digits will be formatted as a US phone number.

Home Phone field value converted into US Phone format.

Code Validators and Converters

If neither SQL or JavaScript is flexible enough, then validation or conversion can be performed with the full power of Microsoft.NET. Code validators and converters are created using the programming language of your project.

Right-click on Customers / Fields / City field node, and press Add Code Converter.

Add Code Converter context menu option in Code On Time's Project Explorer.

Press OK to confirm the creation of a code business rule.

Confirm creation of a code business rule.

On the toolbar, press Generate or Browse to have the code generator produce the source code.

When complete, right-click on Customers / Business Rules / City_Converter node and press Edit Rule in Visual Studio if you want to see the source code.

Edit Rule in Visual Studio context menu option for a business rule in Code On Time web application generator.

The business rule file will open in Visual Studio. The generic handler will look as follows:

C#:

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using MyCompany.Data;

namespace MyCompany.Rules
{
    public partial class CustomersBusinessRules : MyCompany.Data.BusinessRules
    {
        
        /// <summary>
        /// Rule "City_Converter" implementation:
        /// This method will execute in any view before an action
        /// with a command name that matches "Calculate|Insert|Update".
        /// </summary>
        [Rule("r100")]
        public void r100Implementation(string customerID, 
            string companyName, string contactName, string contactTitle, 
            string address, string city, string region, string postalCode, 
            string country, string phone, string fax)
        {
            if (!(String.IsNullOrEmpty(city)) && 
                (this.Arguments.CommandName != "Calculate" ||
                (this.Arguments.Trigger == "City")))
                UpdateFieldValue("City", city.ToUpper());
        }
    }
}

Visual Basic:

Imports MyCompany.Data
Imports System
Imports System.Collections.Generic
Imports System.Data
Imports System.Linq
Imports System.Text.RegularExpressions
Imports System.Web
Imports System.Web.Security

Namespace MyCompany.Rules

    Partial Public Class CustomersBusinessRules
        Inherits MyCompany.Data.BusinessRules

        ''' <summary>
        ''' Rule "City_Converter" implementation:
        ''' This method will execute in any view before an action
        ''' with a command name that matches "Calculate|Insert|Update".
        ''' </summary>
        <Rule("r100")> _
        Public Sub r100Implementation(ByVal customerID As String,
                                      ByVal companyName As String,
                                      ByVal contactName As String,
                                      ByVal contactTitle As String,
                                      ByVal address As String,
                                      ByVal city As String,
                                      ByVal region As String,
                                      ByVal postalCode As String,
                                      ByVal country As String,
                                      ByVal phone As String,
                                      ByVal fax As String)
            If (Not (String.IsNullOrEmpty(city)) AndAlso
                (Not ((Me.Arguments.CommandName = "Calculate")) OrElse
                 (Me.Arguments.Trigger = "City"))) Then
                UpdateFieldValue("City", city.ToUpper())
            End If
        End Sub
    End Class
End Namespace

Let’s try the rule in action. Navigate to the Customers page, and create a new record. Type a value in the City data field.

Lowercase text entered into City field on New Customers form.

Press Tab on your keyboard, or use the mouse to shift focus. The value entered in City will be converted to uppercase.

Text in City converted into uppercase.