HowTo:Use a Java Method to Validate Incoming Data

From AgileApps Support Wiki
Revision as of 23:04, 5 August 2013 by imported>Aeric (Created page with "<noinclude> {{Orientation|Designers|Advanced|10}} </noinclude>In addition to the data validation that is part of every {{type|}}, you can use Java methods to do even more sophist...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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.

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.

    
    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;
    }