Thursday, January 23, 2014

Conditional Validation in K2 SmartForm

I have to admit that currently K2 SmartForm is lack of built-in validation functionality, you can only specify which fields are required to be specified before the form is submitted.

In this post, I will show you a trick how to create a custom validation based on a condition.

Our form (or view) is very simple:

image

It contains:

  • 2 Text boxes which have names: Amount Text Box and Comment Text Area
  • 2 Labels for field header (I ignore the control’s names).

It is a petty cash request form. User can request for specified amount of money and specify notes if needed. Here is the condition:

  • If Request amount >= 1000000 (above or equal to 1 million), user must specify notes.
  • If Request amount < 1000000 (below 1 million), the notes field is optional to be specified.

If we use common validation condition in SmartForm, we can only specify whether field Notes is required or not, we cannot validate Notes based on certain condition.

Here is my trick;

1. Add a text box to Form or View, give it name: Notes. Clear Visible check box in its property. This new text box will act as fake “Notes” text box:

image

 

2. Create some expressions, click the Notes text box (the invisible textbox), select Expressions in property window, click Add to add new expression, give it name Comment is Blank:

image

Create a new expression again and give it name Request Above 1M:

image

Create again a new expression and give it name Notes Validation:

image

Value 9 is random value, you can use any value other than 9.

Make sure the last expression is selected before closing Expression window:

image

 

3. Create rule for click event of Submit button, add validation to the rule:

image

 

4. Specify validation configuration:

image

See validation configuration window above: mark Amount Text Box and Notes (text box) as required. Note that Comment Text Area does not need to be required and do not activate “Do not validate hidden…” option, and activate “Show validation message…”.

Then add Show a Message action if validation passes:

image

Click OK and then click Finish to close message configuration window and Rules Wizard Configuration window.

Click Finish to save the Form / View.

Let’s try to run the Form / View:

If I specify 500000 in Request Amount text box and I do not specify any comments, my request can be submitted:

image

However, if I specify 5000000 in Request Amount text box, the validation will occur:

image

I have to specify something in Notes field (it is Comment Text Area) :

image

You can make the Notes text box becomes visible to see how this trick happens and yes, building forms using K2 SmartForm is very tricky Smile with tongue out

No comments:

Post a Comment