AgileApps Support Wiki Pre Release

HowTo:Use a Java Method to Validate Incoming Data

From AgileApps Support Wiki

For:   Designers
Level: Advanced
Time: 10 minutes

See more:
    ◾ HowTo Guides

In addition to the data validation that is part of every Custom Object, you can use Java methods to do even more sophisticated validation.

In this example, the method ensures that the credit number is in the proper format -- exactly 16 digits, with no characters or spaces. The validation method is designed for the Orders object in the Sample Order Processing System, which has field named credit_card_number. Such a method could be invoked in a Rule Action that is triggered when a new record is created.

This is an important technique for more sophisticated validations. In this case, for example, a credit card number is too big to use a numeric field. The solution is to use a text field, use a data policy to parse the data, and throw an exception in the event of an error.

This code throws an exception if the format isn't valid. The exception will abort the transaction before it is committed.

<syntaxhighlight lang="java" enclose="div">

String ccn_field = "credit_card_number";

public void validate_order(Parameters requestParams) throws Exception {

  String errMsg = "Invalid credit card number format. Needs 16 digits.";
  String ccn = (String) requestParams.get(ccn_field);
  if ((null != ccn) && (ccn.length() != 16)) {
      throw new Exception(errMsg);
  }
  for (int i=0; i<=15; i++) {
     char c = ccn.charAt(i);
     if (c < '0' || c > '9') {
        throw new Exception(errMsg);
     }
  }
  // Format validated
  return;

} </syntaxhighlight>