Skip to content

Validators

Command Options of a Slash Command can have constraints. You can add constraints by annotating the method parameter with the respective annotation.

Default Validators

JDA-Commands comes with the following default constraints:

  • @Perm: The user or member that have the specified discord permission.
  • @NotPerm: The user or member that doesn't have the specified discord permission.

Example

@Command("ban")
public void onBan(CommandEvent event, @NotPerm("ADMINISTRATOR") Member target) {...}

An error message is sent, if a parameter constraint fails:

Validator Error Message

You can customize this error message, find more about it here.

The fail messages of these two default constraints be localized with the localization keys validator.noperm.fail or validator.perm.fail respectively.

Writing own Validators

1. Creating the Annotation

First, you need to create an annotation type for your validator. Your annotation must meet the following conditions:

  • @Target must be ElementType.PARAMETER
  • RetentionPolicy must be RUNTIME
  • Must be annotated with @Constraint defining the valid types for this annotation.

Example

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(String.class)
public @interface MaxString {
    int value();
}

2. Creating the Validator

Secondly, you must create the actual validator by implementing the Validator interface.

The apply(...) method will give you the argument (command option) as well as the annotation object. If the constraint should fail, you must call context.fail(...).

Example

public class MaxStringLengthValidator implements Validator<String, MaxString> {

    public boolean apply(String argument, MaxString annotation, Context context) {
        if (argument.length() < maxString.value()) {
            context.fail("The given String is too long");
        }
    }
}

3. Registration

Lastly, you have to register your new validator.

Example

JDACommands.builder(jda, Main.class)
    .validator(MaxString.class, new MaxStringLengthValidator());
    .start();
@Implementation.Validator(annotation = MaxString.class)
public class MaxStringLengthValidator implements Validator {
    ...
}