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.
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.
Press OK to confirm creation of the business rule.
A validation SQL business rule will be configured to prevent saving of blank values in OrderDate field.
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.
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.
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.
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.
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.
Enter a value in the specified range. When you press OK, the validation test will pass and the record will be saved.
Switch back to the Designer. Right-click on Customers / Fields / City field node. Select Add JavaScript Converter option.
Press Yes to confirm the addition.
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.
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.
Press Tab on your keyboard, or use the mouse to shift focus. The value entered in City will be converted 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.
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.
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.
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.
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.
Press OK to confirm the 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.
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.
Press Tab on your keyboard, or use the mouse to shift focus. The value entered in City will be converted to uppercase.