Ali H
Ali H

Reputation: 381

Hibernate validator in Spring MVC method on String

I have a controller method which takes a String as an argument.
I want to validate the input using hibernate validator, but I really don't want to have to create an object just for this.

Is there any way I can use hibernate validator on a String in line?
If not, feel free to suggest alternative methods of doing this.

Upvotes: 0

Views: 358

Answers (2)

Ramar
Ramar

Reputation: 1564

Please find below the code in a simple Java application using hibernate validator.

package testjarcopy;

import java.lang.reflect.Method;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.executable.ExecutableValidator;

public class TestCopy {

    public static void main(String[] args) throws NoSuchMethodException,
            SecurityException {

        TestCopy object = new TestCopy();
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

        Method method = TestCopy.class.getMethod("placeOrder", String.class, int.class);
        Object[] parameterValues = { "12", 6 };
        ExecutableValidator executableValidator = factory.getValidator().forExecutables();

        Set<ConstraintViolation<TestCopy>> violations = executableValidator.validateParameters(object, method, parameterValues);

        System.out.println("violations.size=" + violations.size());
    }

    public void placeOrder(
            @NotNull @Size(min = 3, max = 5) String customerCode,
            @Min(6) int quantity) {
        System.out.println("running in method..." + customerCode);

    }

}

Below are the dependancies you need to add.

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.1.3.Final</version>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>2.2.4</version>
</dependency>
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>javax.el</artifactId>
    <version>2.2.4</version>
</dependency>

Hope this helps.

Upvotes: 0

Koitoer
Koitoer

Reputation: 19533

You could use this config in your applicationcontext

<bean id="validatorFactory" class="javax.validation.Validation" factory-method="buildDefaultValidatorFactory" />

<bean id="validator" factory-bean="validatorFactory" factory-method="getValidator" />

Then inject this validator in a service or component as it follows.

/**
 * 
 */
@Component
public class ValidationService {

    @Autowired
    private Validator validator;

    /**
     * Check the Set and return the errors that it contains.
     * 
     * @param errors
     * @return Errors found
     * @since Jan 15, 2014
     */
    public String returnErrors(final Set<ConstraintViolation<Object>> errors) {
        final StringBuilder builder = new StringBuilder();
        for (final ConstraintViolation<Object> error : errors) {
            builder.append(error.getMessage());
        }
        return builder.toString();
    }

    /**
     * Validate entities using JSR 303
     * 
     * @param object
     * 
     * @param classes
     * @throws IllegalArgumentException
     * @since Jan 15, 2014
     */
    public void validateEntity(final Object object, final Class<? extends Default>... classes) {
        final Set<ConstraintViolation<Object>> errors = validator.validate(object, classes);
        if (!errors.isEmpty()) {
            throw new IllegalArgumentException(returnErrors(errors));
        }
    }

}

After that you use inject the service in each class you want it and use.

validationService.validateEntity(salesForceForm, PriceChangeRequestGroup.class);

Upvotes: 1

Related Questions