HowTo:Use a Data Policy to Validate Incoming Data
For: Designers See more: |
In addition to the rudimentary data validation that is part of every Custom Object, Data Policies give you the capacity for more sophisticated validation.
In this example, the data policy action ensures that the credit number is in the proper format to begin with. (Exactly 16 digits, with no characters or spaces.) The policy action is designed for the Orders object in the Sample Order Processing System, which has field named credit_card_number.
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, while normal validation mechanisms are limited to simple field comparisons. The solution is to 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. If it were activated in after the triggering event ("post-trigger") then the transaction would have to be rolled back. So it is better practice to configure the data policy so it is activated before the triggering event is carried out.
public void validate_order(Parameters requestParams) throws Exception { // Functions.debug("Validating order"); 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; }