/
Rules Examples

frevvo v9 is no longer supported. Please visit Live Forms Latest for our current Cloud Release. Earlier documentation is available too.

Rules Examples

This chapter contains numerous real world samples of the custom dynamic behaviors you can add to your forms and workflows. Many of the business rules described below are easily created with the Visual Rule Builder. This eliminates the need for the designer to write JavaScript. The Visual Rule Builder provides the functionality to add business logic by simply selecting appropriate functions or controls from your forms/flows using a visual wizard.

The Visual Rule Builder provides the following functions


Use the Operators listed below to build the rule expression


Rules can still be written by manually adding JavaScript in order to build any degree of complex & powerful business logic and integrate with all or your Web Services and frevvo connectors.

Refer to the Visual Rule Builder chapter or watch this webinar for an overview of how to create dynamic forms/flows without writing code.

Calculate Totals

Forms are easier for your users with business logic that automatically calculates subtotals, total, etc..  Here are several common examples:

  • Expense Report Subtotals and Grand Totals.
  • Time Sheets Hours per task, per day and week
  • Purchase Order line Item Costs

Add two fields

 This example uses the sum function adds the values of two fields and displays the result in a Total field.

Your form has three Quantity controls named Q1, Q2 and T respectively. You want to add the values in Q1 and Q2 and display the result in the Total Quantity field. This rule will automatically fire whenever the user types something in Q1 or Q2 and will set the value of Total Quantity appropriately. However, it's important to ensure that the calculated value is valid with respect to the type of Total Quantity. For example, if Total Quantity was of type integer and the computed value of the expression was decimal (such as 1.5), then the rule would be attempting to set an invalid value in T. This is an error. The rule will set the value as requested, but will mark the field as invalid and take appropriate action such as disabling the submit button, displaying the control with a red background etc. Also, if controls are added to the form from the palette, it is important to ensure they have the correct type. For example, for a numeric calculation as described above, the controls should be of type Numeric (found in the palette).

You can use the sum function or just type Q1 + Q2 in the expression field

Action Wizard

Rule List

Action Wizard

Rule List

The sum() function mentioned above will calculate over the entire repeat/table. To use addition to subtotal individual rows, use the "+" operator, i.e. Set Subtotal to Item1 + Item2. 


Multiply Price times Quantity and display results in a Total field

 This example multiplies Price times Quantity and displays the result in a Subtotal field.

Your form/flow has a Price, Quantity and Total Quantity controls. You want to multiply Price times Quantity and display the results in the Total field.

Action Wizard

Rule List


Calculate a Subtotal

 This example computes Subtotals for all the rows in a Table

Imagine you have an Purchase Order workflow with a Table control. The Table has Price,Quantity and a Subtotal column. The fields are named Item_Price, Item_Quantity and Item_Subtotal. You want to multiply the Item_Price times the Item_Quantity and display the results in the Item_Subtotal fields for all the rows in the table. The Rule Builder automatically creates the code to handle adding/deleting table rows.

Action Wizard

Rule List

Calculate a Grand Total

 This example calculates a Grand Total by adding the Subtotal values

Now you want to add a Grand Total field to your Purchase Order workflow. The Grand Total field contains the sum of the Subtotal fields in each row of the table. Add a Money control to your form/flow and name it Grand Total. Use the Rule Builder to create the rule. The Rule Builder automatically creates the code to handle adding/deleting table rows.

Action Wizard

Rule List

Show or Hide Controls and Workflow Steps

Often forms/flows need fields that are only used depending on the answers to prior form fields. For example, if your form requires both a Shipping Address and Billing Address but the your form user has checked  "Shipping is the same as Billing Address" then it's nice to not clutter the form with the unnecessary Shipping Address input fields. You can use rules to hide the Shipping Address and show it only when the form user says they are different.

The easiest way to create a Show/Hide rule is to use the Visual Rule Builder. Here are common reasons for using Show/Hide:

  • Show/Hide a section
  • Show a Message to the user to alert them to either an error or success condition
  • Show a Details Text Area when as user clicks Yes to "Would you like to describe your issues in detail?"
  • Show a Signature or Signed Section when the workflow reaches the approval step.
  • Show/Hide a Tab on a Workflow Step

See the documentation for Data Sources and Schemas for details on implementing a Show/Hide rule with XSD controls.

Show the Shipping Address if it is different from the Billing Address

 This example shows the Shipping Address section if it is different from the Billing Addres

Your form contains a Billing Address section, a hidden Shipping Address section named S and a Radio control named B that asks the question - "Is the Shipping Address different from the Billing Address?" If the Billing and Shipping addresses are the same there is no need to clutter the form with the unnecessary Shipping Address input fields. You can use rules to hide the Shipping Address and show it only when the form user says they are different. This rule will automatically fire whenever the user checks or unchecks B and will show/hide the shipping address section S. In this example, you would typically set the checkbox B to be initially unchecked and the section S to be initially hidden.

Condition, Action and Else Action wizards

Rule List

Show a Message based on Selections in Other controls

 This example shows a Message when specific options are selected in the Facility and CompanyFacility fields

This form has a radio control named Facility and a second radio control named CompanyFacility. This rule makes a message control named Msg visible depending on the selected options. If Boston is selected for the Facility control OR New York is selected for the the CompanyFacility control, the hidden message control will display. Use the Rule Builder to create this rule - remember to change the "and" to "or" in the Logic expression so the rule will execute if either condition is met.

Condition, Action and Else Action wizards

Rule List

Show a Message if a control contains data

 This example shows a Message if there is a value in another control

This rule makes the message control nickNameThankYou visible when the user enters a value into the Nickname input text control. And then hides the message control if the user deletes the value in Nickname.

Show Tabs on specified flow steps

 This example will Show a Hidden Tab on a Workflow Step

Step 1 of the flow has a Tab control with a tab named Employee and a second tab named Review. This rule makes a tab named Review visible only when the workflow is on the step named Manager Review(Step 2).



Condition, Action and else Action wizards

 

Rule List

Show/Hide Submit & Cancel

This rule is not yet supported in the Visual Rules Builder and thus still requires some JavaScript.

You have a form with multiple tabs. The main tab contains the form and the other tabs contain reference information users may need when completing the form. You only want the submit and cancel buttons visible when the user is in the main tab. This rule hides the submit and cancel buttons when the reference tabs are selected. The control name of the main tab is MainTab. Be sure to select the Main Tab in the designer then save the form. This ensures the Main Tab will be selected when the form loads and the rule will run.

You can write the rule using the if...else conditional statement shown in the example on the left or the shortened syntax shown on the right:

if (!(MainTab.selected)) {
    Submit.visible = false;
    Cancel.visible = false;
} else {
   Submit.visible = true;
   Cancel.visible = true;
}
 Submit.visible = Cancel.visible = (MainTab.selected);





Show/Hide Approval Sections on specified flow steps

 This example shows the Accounts Payable Approval section only on the Accounts Payable step of the flow

You are designing an Expense Report workflow that has a total of 3 steps. Steps 2 (Manager Approval step) and step 3 (Accounts Payable step) are Linked Steps.

  • Step 1 is filled in by the employee. When it is completed, the flow is routed to the employee's manager for Approval/Rejection
  • Step 2 is performed by the Manager. If the Manager approves, the workflow is routed to the Accounts Payable group for final processing.
  • Step 3 is performed by the first person in the Accounts Payable group to click the perform icon on their Task List for this workflow.

Step 1 has a Section named Manager Approval and a section named Accounts Payable. The Visible property on both these sections is unchecked so they are hidden by default.  You want to hide the Manager Approval and Accounting sections for the first step, show the Manager Approval section when the second step is performed by a manager and show the Manager Approval and Accounting sections when the third step is performed by an Accounting department employee.

This rule shows the section named Accounts Payable Only if the workflow is on the Accounts Payable step. It should not be visible when the workflow is on the steps performed by the employee or the manager.

The Condition, Action and Else Action wizards for this rule are shown in the image. The dropdown for the current step value displays the linked steps as choices.

Rule List

This rule will show the Manager Approval section on both the Manager and Accounts Payable step. Note the use of the When current step is on or after Manager condition

Step 2 - Displays the Manager Approval section

Step 3 - Displays the Manager Approval AND the Accounts Payable sections

Rule List

Printable

Business rules often are used to control what is printed to the final form PDF.

This form has a radio control named DescribeInDetail and a section control named Details. Details is hidden by default and made visible if the user selects 'Yes'.

When the form is submitted we've configured  to send an email with the form PDF. We only want the Details section to appear on the PDF when the user selects 'Yes'. So we uncheck the printable property on the section control. This property will apply to the section and all controls inside the section. So we do not have to uncheck printable on the inner controls. Then we create this business rule with the Visual Rule Builder. When the section is visible we also set it to be printable. When the section is hidden we also set it to be not printable.

 Click here for an example of this rule in the Rule Builder

 

Pattern

In most cases, the Pattern property can be set directly in the form designer's control properties panel. However, consider a case where you have an existing workflow with pending tasks that contains a control with no pattern set on the first step. The data in the in-flight flows may or may not be consistent with the pattern. If you edit the production workflow to set a pattern on the control, that control could become invalid on in-flight workflow instances that are on later steps and can't be edited. This will prevent those in-flight tasks from being submitted. In this case, you can use a business rule to set the pattern on this control only when the workflow is on the first step. This rule will enforce the pattern on all new workflow interviews but will not break in-flight workflows.

You might also use this method when a control's pattern has an either/or scenario. In this example, the control should be valid if four numerical digits are entered, or if the word "NONE" is entered in any letter case, e.g. "none" or  "None".

var event = form.load;
var uc = SSN.value;
var res = uc.toUpperCase(); //change text to uppercase to simplify value comparison

if (frevvo.step.on('_72odfp6qEeuqr9Bz_J-qDw')){ //if the current step is Step 1

  if (res === 'NONE'){
    SSN.valid = true;
  } else if (res !== 'NONE'){
    var pattern = /^[0-9]{4}$/g;
    SSN.valid=uc.match(pattern)?true:false;
  }
}

How it works

The Pattern property is not directly accessible by business rules. However, you can set the desired pattern in a variable and use the JavaScript match method with the conditional operator '?' to compare the control's value to the desired pattern. Set the control's valid property to the result of the match condition, which is true if the variables match and false if they do not match. Be sure to set a meaningful Error Message, which will appear whenever the valid property is false and prompt the user to enter a valid value.

Dynamically Send Email

Let's say you have a form or workflow step that should send an email only under certain conditions. In the example below, the Account Receivable form will only send an email to the Client Services Manager if the payment is related to a services project. 

 Click here to see an example of this in the Visual Rule Builder.

To dynamically send an email, add a hidden email control (SendtoCSEmail) to your form.

In the Email Doc Action (or Email tab for a workflow step), enter the control name as a template in the "To" field.

Use the Visual Rule Builder to fill the hidden email control with the valid email if the condition is true, and a no-reply email if the condition is false. The Else Action is important here - if you set it to Empty or to an invalid string (any string not using the syntax <name>@<name>.<string>), you will get a submission error.

You can also set the hidden email to a template so that it is evaluated at run time.

When the user clicks Submit or Continue, the email will send to either the valid email (condition=true) or the noreply email (condition=false.)

Enable/Disable Controls

Submit/Continue Button Disabled

A great feature of is the fact that a form cannot be submitted or a flow cannot be continued to the next step until all required fields are filled and all filled fields have valid data (eg. a date field must contain a valid date). Sometimes it might not be as obvious to the form/flow user why the form/flow will not submit or continue to the next step.  provides a built-in feature to show validation errors at the time of submission. Refer to the Invalid Form Notification for Users  topic to see how it works.

Enable/disable a question

You have a form with two controls and you have assigned them Names B and Q respectively. B is a checkbox with a single option - Yes. . If checked, you wish to ask an additional question in Q. Use the Rule Builder to create this rule. Be sure to slide the toggle icon to enter the literal value Yes on the Condition wizard.

 This example enables an additonal question based on the answer to a previous question

 

Condition Wizard

Rule List

This rule will automatically fire whenever the user checks or unchecks B and will enable/disable the question in Q. In this example, you would typically set the checkbox B to be initially unchecked and the control Q to be initially disabled.

Formatting money values to display in a Message Control

This rule is not yet supported in the Visual Rules Builder and thus still requires some JavaScript.

Let's say you have calculated a sum in a Number control in your form and you want to display it in a Message control and format it as a money value with commas and decimal places.  You will need a Number control named Num and a message control named Message in your form. This rule will display the number entered in the number control with commas. If the user enters 5600.44 in the number field then the result in the message control would look like this:"5,600.44".

var x, x1, x2;
if (Num.value > 0) {
    var nStr = Num.value.toFixed(2);
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
 x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    Message.value = '$' + x1 + x2;
}

Format Money in Text Controls

This rule is not yet supported in the Visual Rule Builder and thus still requires some JavaScript.

You may want to format money with currency signs, commas, decimals and rounded to two decimal places. This example uses a text control for input and a business rule to format the money value.


var x, x1, x2;

var numberWithCommas = function(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
var formatMoney = function(amt) {
  var decimalAmount = Math.round(amt * 100) / 100;
  return numberWithCommas(decimalAmount.toFixed(2));

};
if (Amount.value.length > 0) {
    var m = Amount.value.replace(/\$/g,"").replace(/,/g, "");
    var formattedMoney = formatMoney(m);
    Amount.value = '$' + formattedMoney;  
}


Here is another example showing a text control named "Money" in a table. Another text control named "Total" displays the column total.

var x, x1, x2;

var tot = 0;
var numberWithCommas = function(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};
var formatMoney = function(amt) {
  var decimalAmount = Math.round(amt * 100) / 100;
  return numberWithCommas(decimalAmount.toFixed(2));

};

if (Money.value.length > 0) {
  for (var i = 0; i < Money.value.length; i++) {
    var m = Money[i].value.replace(/\$/g,"").replace(/,/g, "");
    var formattedMoney = formatMoney(m);
    Money[i].value = '$' + formattedMoney;
    tot = tot + Number(m);
  }
  var formattedTotal = formatMoney(tot);
  Total.value = '$' + formattedTotal;
}

European Number Format

You may need to display numbers in a locale-specific format. While current versions of frevvo do not support javascript locale methods on number controls, you can write a business rule to handle displaying numbers in your desired format. This example displays a number with a period as the thousands separator and a comma as the decimal separator, i.e. 10.000,00. You can modify this rule slightly for other formats, such as using a space as the thousands separator. 

There is a text control in the form named EuropeanFormat.

//use a decimal as thousand separator
var numberWithDecimals = function(x) {
  return x.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
};

//format with two decimals
var formatNumber = function(amt) {
  var decimalAmount = Math.round(amt * 100) / 100; // this adds a decimal with two zeros after the number.
  return numberWithDecimals(decimalAmount.toFixed(2));
};

if (Boolean(EuropeanFormat.value) && Boolean(EuropeanFormat.value)) {
  var e =  parseInt(EuropeanFormat.value.replace(/,/g, ''), 10); 
  var f = formatNumber(e); //format the value using above functions
  var intIndex = f.lastIndexOf(".");
  f = f.slice(0, intIndex) + f.slice(intIndex).replace(".", ",");//change the last decimal to a comma
  EuropeanFormat.value = f;
}

Here is the form in use mode:


This rule is similar to the format money rule above, in that it adds a decimal with two zeroes behind the number entered, so 12345 displays as 12.345,00. If you'd rather convert the number to a decimal as entered, simply remove the '* 100' from the Math.round() method parameters. This change will display 12345 as 123,45.

Rounding a Number to a Specified Number of Decimal Places

Let's say you have a Time Sheet where you collect the number of hours worked per day and total them in a Line Total field. Your form consists of Number controls for the hours and a Number control for the total. When testing your form, you enter values with decimal points and notice the total unexpectedly calculates to a number with many decimal places.

This is JavaScript behavior when calculating decimal point addition. 
Method 1: Use the built-in toFixed(n) function to truncate the result to n number of decimal places as shown in the rule below:


var x;
x = (testone.value + testtwo.value + testthree.value + testfour.value + testfive.value + testsix.value);
LineTotal.value = x.toFixed(2);


Method 2: You can also round numbers using the round function in the Visual Rule Builder in the format:

round(num, decimalDigits)

Method 3: Another approach would be to assign Patterns that limit the number of decimal places.

Split Phone Number

There may be cases where you collect data from the user in one format, such as a phone number, but you need to use it in another format, such as in two different fields on a mapped PDF. You can use standard JavaScript methods to accomplish this. Here is an example that uses split() and also strips the separators (- or .) from the resulting values. You can use a similar method to split emails or other text as well.

Rule Code
var p = PhoneNumber.value;

if (PhoneNumber.value.includes('-')){
  var split = p.split("-");

  AreaCode.value = split[0];
  Number.value = split[1] + split[2];
}else if (PhoneNumber.value.includes('.')){
  var split = p.split(".");
    
  AreaCode.value = split[0];
  Number.value = split[1] + split[2];

} else {
  AreaCode.value = p.substring(0, 3);
  Number.value = p.substring(3,10);
}

The result places the split values in two separate controls at run time. These controls would typically be hidden in use mode and mapped to the PDF.

Textarea Max Length

This rule is not yet supported in the Visual Rules Builder and thus still requires some JavaScript.

In html there is no way to set a maxLength on a textarea control. This is why the textarea control does not have a maxlength property like the text control does. It is possible to do this via a business rule. This example form has a textarea control named 'Desc' where the user can enter up to a 500 character description. On this control we also set the ErrorMsg property to the string 'You must limit your description to 500 characters'. This message is automatically displayed when the description control is set to invalid by the following business rule.

if (Desc.value.length > 500) {
  Desc.valid = false; 
} else {
  Desc.valid = true; 
} 

You can even customize the error message by adding this line to your rule. Now the error message will tell the user how many characters they are over the maximum allowed.

Desc.status = 'Invalid. Max 20 chars allowed and you have ' + Desc.value.length; 

Set One or the Other Control to Required

Consider a health insurance policy request form in which Employee election or the Family election is required, but not both. Additionally, if one is selected, you want to clear any value that might be in the other (e.g. if the user selected Employee, then changed their mind and selects Family, you must clear the Employee selection.)

In this example we are using two radio controls in the form; one for “Employee Only” and the other for “Family”. The options available for both controls are Accept and Waive. The user must select either one of the radio control to proceed.

You can initially set both controls to required, then use business rules to set one control to optional when the other is filled, and vice versa. To use the Visual Rule Builder, you would need two rules. In JavaScript rule code, you could combine them if desired.

Rule 1: Set Employee-Only to Optional & Empty if Family is selected. If the user selects family, this rule sets the employee-only radio control to optional and empty. The else action sets the employee-only radio control to required.

Condition Wizard

Action Wizard

Else Action Wizard

Rules List

Rule 2, "Set Family to Optional & Empty if Employee is selected", is similar and is shown in the Rules List below. If the use selects employee-only, this rule sets the family radio control to optional and empty. The else action sets the family radio control to required.

At runtime, both controls are required at first. As soon as one control is filled the other control is set to optional and vice versa. Notice that if you change your selection, the opposite control value is cleared.

Required Field Status in Accessible Forms

This rule is not yet supported in the Visual Rules Builder and thus still requires some JavaScript.

You can build forms/flows In that meet Section 508 and WCAG 2.0 accessibility standards. Accessible forms/flows can assist users with visual and motor impairments. When the Accessible property is enabled for a form/flow, the error, "You can't leave this empty <control name>"  displays, if users move ahead from a required field without filling it. The status property for the empty control becomes invalid and sets the error message. Normally, the status property can be used in a business rule. For example, let's say a form has a text control named 't', and a message control named "m". If you write a rule to update the message field (control named m) with the STATUS of the required/invalid control (control named t), as shown below, it will not work because the "You can't leave this empty" message for a required control is not treated as it's status.

if(!t.valid)
  {
    m.value = t.status;
  }

If the rule is written this way, it will fill the message control with the errmsg from the invalid text control.

if (!t.valid) {
  if (t.value.length