Skip to content
dapz edited this page Feb 11, 2014 · 3 revisions

The domain of the arguments is usually not the whole range allowed by the supported types such as Int, String, etc. This is where validation can be used, to restrict the argument input to a particular set of values or impose other requirements on the arguments.

Predefined Validations

Sumac already provides a number of predefined validators that can be added by using annotations on the fields, these are:

  • @Required, the field has to be provided on the command line, otherwise a ArgException will be thrown.
  • @Positive, the numeral field should be greater than 0.
  • @Range(min=a,max=b), the numeral field should be within a specific range

Custom one-shot validations

Every argument holder can also ensure it received valid arguments via custom validation rules.

import com.quantifind.sumac.FieldArgs

trait MyArgs extends FieldsArgs {
  var count: Int = 16
  addValidation{ require(count%2 == 0, "count must be even")}
}

Custom validation annotations

You can also "easily" create your own annotation for simplifying reusability. First define the annotation in java:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ThreeOrFour {}

then in your arg class, you can associate a function with the annotation with a call to registerAnnotationValidation

import com.quantifind.sumac.{FieldArgs, ArgException}

class UserDefinedAnnotationArgs extends FieldArgs {
  @ThreeOrFour
  var x: Int = _

  registerAnnotationValidation(classOf[ThreeOrFour]){(default, value, annotation, name) =>
    if (value != 3 && value != 4) {
      throw new ArgException(name + " must be 3 or 4")
    }
  }
}

Note that you'd normally just call registerAnnotationValidation once, in your base trait

Clone this wiki locally