CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-jakarta-validation--jakarta-validation-api

Jakarta Validation API defines a metadata model and API for JavaBean and method validation

Pending
Overview
Eval results
Files

bean-validation.mddocs/

Bean Validation

Primary validation interface for validating JavaBean objects, properties, and values with comprehensive constraint violation reporting and property path navigation.

Capabilities

Validator Interface

Main interface for performing validation operations on objects, properties, and values.

/**
 * Primary interface for validating beans, properties, and values
 * Implementations must be thread-safe and can be cached
 */
interface Validator {
    /**
     * Validate all constraints on the provided object
     * @param object object to validate
     * @param groups validation groups to apply (optional)
     * @return set of constraint violations, empty if valid
     * @throws IllegalArgumentException if object is null
     */
    <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups);
    
    /**
     * Validate constraints on a specific property of an object
     * @param object object containing the property
     * @param propertyName name of the property to validate
     * @param groups validation groups to apply (optional)
     * @return set of constraint violations for the property
     * @throws IllegalArgumentException if object is null or propertyName is invalid
     */
    <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups);
    
    /**
     * Validate constraints on a property value without requiring an object instance
     * @param beanType class of the bean containing the property
     * @param propertyName name of the property
     * @param value value to validate
     * @param groups validation groups to apply (optional)
     * @return set of constraint violations for the value
     * @throws IllegalArgumentException if beanType is null or propertyName is invalid
     */
    <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups);
    
    /**
     * Get validation metadata for a class
     * @param clazz class to get constraints for
     * @return BeanDescriptor containing validation metadata
     * @throws IllegalArgumentException if clazz is null
     */
    BeanDescriptor getConstraintsForClass(Class<?> clazz);
    
    /**
     * Get ExecutableValidator for method and constructor validation
     * @return ExecutableValidator instance
     */
    ExecutableValidator forExecutables();
    
    /**
     * Unwrap the Validator to a specific implementation type
     * @param type target type to unwrap to
     * @return unwrapped validator instance
     * @throws ValidationException if unwrapping is not supported
     */
    <T> T unwrap(Class<T> type);
}

Usage Examples:

import jakarta.validation.*;
import jakarta.validation.constraints.*;
import java.util.Set;

// Bean definition with constraints
class Person {
    @NotNull
    @Size(min = 2, max = 50)
    private String name;
    
    @Min(0)
    @Max(150)
    private int age;
    
    @Email
    private String email;
    
    @Valid
    private Address address;
    
    // constructors, getters, setters...
}

// Validation examples
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

// 1. Validate entire object
Person person = new Person("", -5, "invalid-email");
Set<ConstraintViolation<Person>> violations = validator.validate(person);

for (ConstraintViolation<Person> violation : violations) {
    System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
}
// Output: 
// name: size must be between 2 and 50
// age: must be greater than or equal to 0
// email: must be a well-formed email address

// 2. Validate specific property
Set<ConstraintViolation<Person>> nameViolations = 
    validator.validateProperty(person, "name");

// 3. Validate value without object instance
Set<ConstraintViolation<Person>> emailViolations = 
    validator.validateValue(Person.class, "email", "test@example.com");

Constraint Violation

Interface describing a single constraint violation with detailed information about the validation failure.

/**
 * Describes a constraint violation with detailed context information
 * @param <T> type of the root bean
 */
interface ConstraintViolation<T> {
    /**
     * Get the interpolated error message for this constraint violation
     * @return human-readable error message
     */
    String getMessage();
    
    /**
     * Get the non-interpolated error message template
     * @return message template with placeholders
     */
    String getMessageTemplate();
    
    /**
     * Get the root bean being validated
     * @return root bean instance or null if validating a class
     */
    T getRootBean();
    
    /**
     * Get the class of the root bean
     * @return root bean class
     */
    Class<T> getRootBeanClass();
    
    /**
     * Get the leaf bean containing the constraint violation
     * @return leaf bean instance
     */
    Object getLeafBean();
    
    /**
     * Get method/constructor parameters when validating executables
     * @return parameter array or null if not validating executables
     */
    Object[] getExecutableParameters();
    
    /**
     * Get method/constructor return value when validating executables
     * @return return value or null if not validating return values
     */
    Object getExecutableReturnValue();
    
    /**
     * Get the property path from root bean to the constraint violation
     * @return Path describing navigation from root to violated property
     */
    Path getPropertyPath();
    
    /**
     * Get the value that failed validation
     * @return invalid value
     */
    Object getInvalidValue();
    
    /**
     * Get metadata about the violated constraint
     * @return ConstraintDescriptor for the violated constraint
     */
    ConstraintDescriptor<?> getConstraintDescriptor();
    
    /**
     * Unwrap the ConstraintViolation to a specific type
     * @param type target type to unwrap to
     * @return unwrapped instance
     * @throws ValidationException if unwrapping is not supported
     */
    <U> U unwrap(Class<U> type);
}

Property Path Navigation

Interface for navigating property paths from root objects to constraint violations.

/**
 * Path from an object to another in an object graph
 * Immutable and thread-safe
 */
interface Path extends Iterable<Path.Node> {
    /**
     * String representation of the path using dot notation
     * @return path as string (e.g., "person.address.street")
     */
    String toString();
    
    /**
     * Base interface for path nodes
     */
    interface Node {
        /**
         * Get the name of this node (property name, method name, etc.)
         * @return node name or null for certain node types
         */
        String getName();
        
        /**
         * Check if this node represents an iterable element
         * @return true if node is in an iterable (List, Set, etc.)
         */
        boolean isInIterable();
        
        /**
         * Get the index if this node represents an indexed element
         * @return index or null if not indexed
         */
        Integer getIndex();
        
        /**
         * Get the key if this node represents a keyed element (Map)
         * @return key or null if not keyed
         */
        Object getKey();
        
        /**
         * Get the kind of element this node represents
         * @return ElementKind enum value
         */
        ElementKind getKind();
        
        /**
         * Cast this node to a specific node type
         * @param nodeType target node type
         * @return node cast to specified type
         * @throws ClassCastException if cast is not valid
         */
        <T extends Path.Node> T as(Class<T> nodeType);
    }
    
    /**
     * Node representing a bean
     */
    interface BeanNode extends Node {
        /**
         * Get the container element type index for container element nodes
         * @return type argument index or null
         */
        Integer getTypeArgumentIndex();
    }
    
    /**
     * Node representing a property
     */
    interface PropertyNode extends Node {
        /**
         * Get the container element type index for container element nodes
         * @return type argument index or null
         */
        Integer getTypeArgumentIndex();
    }
    
    /**
     * Node representing a method
     */
    interface MethodNode extends Node {
        /**
         * Get the parameter types of the method
         * @return list of parameter types
         */
        List<Class<?>> getParameterTypes();
    }
    
    /**
     * Node representing a constructor
     */
    interface ConstructorNode extends Node {
        /**
         * Get the parameter types of the constructor
         * @return list of parameter types
         */
        List<Class<?>> getParameterTypes();
    }
    
    /**
     * Node representing a method return value
     */
    interface ReturnValueNode extends Node {
        /**
         * Get the container element type index for container element nodes
         * @return type argument index or null
         */
        Integer getTypeArgumentIndex();
    }
    
    /**
     * Node representing a method/constructor parameter
     */
    interface ParameterNode extends Node {
        /**
         * Get the parameter index
         * @return parameter index
         */
        int getParameterIndex();
        
        /**
         * Get the container element type index for container element nodes
         * @return type argument index or null
         */
        Integer getTypeArgumentIndex();
    }
    
    /**
     * Node representing cross-parameter constraints
     */
    interface CrossParameterNode extends Node {}
    
    /**
     * Node representing a container element
     */
    interface ContainerElementNode extends Node {
        /**
         * Get the container element type index
         * @return type argument index
         */
        Integer getTypeArgumentIndex();
    }
}

Constraint Violation Exception

Exception containing constraint violations, typically thrown by frameworks when validation fails.

/**
 * Exception containing constraint violations
 * Typically thrown by frameworks when validation fails in certain contexts
 */
class ConstraintViolationException extends ValidationException {
    /**
     * Create exception with a set of constraint violations
     * @param constraintViolations set of violations
     */
    ConstraintViolationException(Set<? extends ConstraintViolation<?>> constraintViolations);
    
    /**
     * Create exception with message and constraint violations
     * @param message exception message
     * @param constraintViolations set of violations
     */
    ConstraintViolationException(String message, Set<? extends ConstraintViolation<?>> constraintViolations);
    
    /**
     * Get the constraint violations
     * @return unmodifiable set of constraint violations
     */
    Set<ConstraintViolation<?>> getConstraintViolations();
}

Usage Examples:

// Working with constraint violations
Set<ConstraintViolation<User>> violations = validator.validate(user);

if (!violations.isEmpty()) {
    for (ConstraintViolation<User> violation : violations) {
        // Get violation details
        Path propertyPath = violation.getPropertyPath();
        Object invalidValue = violation.getInvalidValue();
        String message = violation.getMessage();
        
        // Navigate path nodes
        for (Path.Node node : propertyPath) {
            System.out.println("Node: " + node.getName() + 
                             ", Kind: " + node.getKind() + 
                             ", Index: " + node.getIndex());
        }
        
        // Get constraint metadata
        ConstraintDescriptor<?> descriptor = violation.getConstraintDescriptor();
        System.out.println("Constraint: " + descriptor.getAnnotation().annotationType().getSimpleName());
    }
}

// Handling exceptions
try {
    // Some framework operation that validates
    someFrameworkMethod(invalidObject);
} catch (ConstraintViolationException e) {
    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    // Handle violations...
}

Install with Tessl CLI

npx tessl i tessl/maven-jakarta-validation--jakarta-validation-api

docs

bean-validation.md

bootstrap-configuration.md

constraints.md

container-validation.md

custom-constraints.md

index.md

metadata.md

method-validation.md

validation-groups.md

tile.json