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:

  • @Role: The member must have the specified guild role.
  • @NotRole: The member must not have the specified guild role.
  • @User: Must be the specified user or member
  • @NotUser: Must not be the specified user or member.
  • @Perm: The user or member that have the specified discord permission.
  • @NotPerm: The user or member that doesn't have the specified discord permission.

The user and role annotations will resolve the snowflake entity dynamically using the respective type adapter. This means that you can either pass an ID or a name.

Example

@SlashCommand("ban")
public void onBan(CommandEvent event, @NotRole("Admin") 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.

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.
  • Must contain a message() field for the error message

Example

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

    int value();

    String message() default "The given String is too long";

}

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 untyped, you must cast them on your own. If the constraint shall pass, you must return true, if it fails false.

Example

public class MaxStringLengthValidator implements Validator {

    @Override
    public boolean apply(Object argument, Object annotation, InvocationContext<?> context) {
        MaxString maxString = (MaxString) annotation;
        return String.valueOf(argument).length() < maxString.value();
    }

}

3. Registration

Lastly, you have to register your new validator.

Example

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