Validation procedures

Validation procedures can be used to validate input such as HTTP requests. Its normal usage is during authentication or registration, where form parameters need special validation. A phone number needs a certain format, or additional fields during registration needs validation.

A validation procedure has the following structure:

Listing 251 Structure of Validation procedures
1
2
3
4
5
6
7
function result(validationContext) {
  var errors = {};

    // validate the object

    return errors;
}

Important

The main function of a validation procedure must be called result.

Common API

Validation procedures have access to all of the Common Procedure API.

Function

The result function takes one argument, which is the context object that gives access to the request to be validated.

The type of the context object is ValidationProcedureContext.

result(validationContext)

The main function of a transformation procedure

Arguments:
  • validationContext – The context object for validation procedures
Returns:

a map of errors if validation fails, or an empty map on successful validation.

Return Value

The returned value should be a JavaScript object representing the validation errors that were found. If the object is valid, an empty object should be returned. Otherwise, the object should contain entries of the form:

{ "fieldName" : "message.key" }

These message keys are then used in the the templates shown to the end user to present a localized error message.

Examples

A good example is during registration when a Form is validated and the username field is expected to contain a String with at least 2 characters. If that data fails to validate we want to show a localized message to the user. For this we return a message key that we define validation.username_too_short.

Listing 252 Username length validation procedure
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function result(validationContext) {
  var errors = {};
  var username = validationContext.request.getFormParameter("userName");

  if ((typeof username == "string") && username.length < 2) {
      errors.username = "validation.username_too_short";
  }

  return errors;
}

Another common scenario is to add additional parameters to the form that the user should enter. A good example is a check box for accepting license terms. A validation procedure can be added to validate that the checkbox is checked before accepting the request.

Listing 253 Validate terms of service
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function result(validationContext) {
  var errors = {};

  var acceptTerms = validationContext.request.getFormParameter("agreeToTerms");

  if (acceptTerms !== 'on')
  {
      errors.terms = "error.validation.terms";
  }

  return errors;
}