Basic Data Validation

Basic Data Validation

You can test data before setting field value and take appropriate action. This may include the following:

  • Truncating string data to fit.
  • Alerting the user of a problem so that the user can address it manually.
  • Canceling the action.

A common scenario for form scripting is to set the value of one integer field based on the values found in two other fields. On the surface the code to achieve this might appear simple. For example if you have three custom integer fields the following code will work most of the time if put in the OnChange event of the fields that are factors in the equation or in the OnSave event of the form.

// Get a reference to all three fields.
var fieldA = crmForm.all.new_fielda;
var fieldB = crmForm.all.new_fieldb;
var fieldC = crmForm.all.new_fieldc;
// Do the calculation.
fieldC.DataValue = fieldA.DataValue * fieldB.DataValue;

The following example shows a more sophisticated approach that considers that the product of the equation may exceed the limits on the third field. This same code (except for one line) is applied to the OnChange event of both of the fields that are factors in the equation.

// Get a reference to all three fields.
var fieldA = crmForm.all.new_fielda;
var fieldB = crmForm.all.new_fieldb;
var fieldC = crmForm.all.new_fieldc;
// If Field A has no value, set the user's 
// pointer on Field A so that they can add data and do not set field C.
if (fieldA.DataValue == null)
{
   fieldA.SetFocus();
   return;
}
// Do the same for Field B.
if (fieldB.DataValue == null)
{
   fieldB.SetFocus();
   return;
}

// After establishing that both fields have data, 
// set the value of field C if it does not exceed the capacity.
var test = fieldA.DataValue * fieldB.DataValue;
if ((test < fieldC.Max) && (test > fieldC.Min))
{
   fieldC.DataValue = test;
}
else
{
   alert("The value of the calculation exceeds the capacity of Field C.")

   // This field reference depends on which field the script 
   // is configured for (either A or B). 
   // The current value should be set to null.
   fieldB.DataValue = null;
   // fieldA.DataValue = null;

   // You want to cancel out the value that was previously changed.
   fieldC.DataValue = null;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s