Skip to content

Validation exception

zhaber edited this page Aug 2, 2012 · 3 revisions

Besides returning the boolean value false from a validator, there is one more way to indicate invalid input — the ValidationException. This class contains several constructors: the first one takes a map with error properties (Map<String, Object>), the second, an error message represented by a String object, and the third constructor takes no parameters. You can pass any key/value pairs to the constructor, but the following error property names have a special meaning:

  • element is the element next to which an error message will be shown
  • errorCode is any object that identifies the error
  • message is the error description
  • url is a redirect URL

For example, the exception can be thrown from a converter to indicate that some precondition required for successful normalization of an input value is violated:

int toInt(String value) { 
  try { 
    Integer.valueOf(value)) {
  catch (NumberFormatException e) {
    throw new ValidationException(e.message)
  }
}

Another usage example would be a validator for password strength:

boolean isStrongPassword(String value, List<String> mediumRegexps, 
    List<String> strongRegexps) {
  if (!mediumRegexps.every({value.matches(it)})) {
    throw new ValidationException(PasswordStrength:
        PasswordStrength.WEAK)
  } else if (!strongRegexps.every({value.matches(it)})) {
    throw new ValidationException(PasswordStrength: 
        PasswordStrength.MEDIUM)
  } else {
    true
  }
}