Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

Spring MVC - Custom Validation

In Spring MVC, you can easily implement custom validation for your forms using the validation API. This often involves using the @Valid annotation in combination with custom annotations or implementing the Validator interface. Below are steps to create custom validation in Spring MVC:

1. Custom Annotation

Let's say we want to validate that a string field isn't containing some restricted words. First, create a custom annotation:

@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = RestrictedWordsValidator.class)
public @interface NoRestrictedWords {
    String message() default "Contains restricted words";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

2. Custom Validator

Implement the validation logic:

public class RestrictedWordsValidator implements ConstraintValidator<NoRestrictedWords, String> {

    private List<String> restrictedWords = Arrays.asList("restricted", "forbidden", "banned");

    @Override
    public void initialize(NoRestrictedWords constraintAnnotation) {
        // Initialization code, if required
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) return true;
        
        return restrictedWords.stream()
            .noneMatch(word -> value.toLowerCase().contains(word));
    }
}

3. Use the Custom Validation

Apply the custom validation annotation to your model fields:

public class CommentForm {
    
    @NoRestrictedWords
    private String comment;

    // Getters, setters, etc.
}

4. Controller

In your controller, ensure you use @Valid to trigger validation:

@PostMapping("/submitComment")
public String submitComment(@ModelAttribute @Valid CommentForm commentForm, BindingResult result) {
    if (result.hasErrors()) {
        return "commentForm"; // return to the form page if there are errors
    }
    // process the form and redirect
    return "successPage";
}

5. Display Validation Errors in the View

You can display validation errors in your view (commentForm.jsp for example):

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:form modelAttribute="commentForm">
    <form:textarea path="comment" />
    <form:errors path="comment" cssClass="error" />
    <input type="submit" value="Submit Comment" />
</form:form>

6. Message Source

Optionally, define a custom validation message in messages.properties:

NoRestrictedWords.comment=Your comment contains some inappropriate words. Please correct them.

And ensure you have a MessageSource bean configured:

@Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
}

This way, Spring will display a more user-friendly message when the validation rule is violated. Adjust the configuration based on your application's specific requirements.

  1. Custom validation annotations in Spring MVC:

    Spring MVC allows you to create custom validation annotations by defining your annotation and associating it with a custom validator class. This helps in making your validation code more expressive and reusable.

    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = CustomValidator.class)
    public @interface CustomValidation {
        String message() default "Invalid value";
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    }
    
  2. Creating custom validators in Spring MVC:

    Custom validators in Spring MVC are classes that implement the Validator interface. You need to override the validate method to define your custom validation logic.

    public class CustomValidator implements Validator {
        @Override
        public boolean supports(Class<?> clazz) {
            return YourForm.class.isAssignableFrom(clazz);
        }
    
        @Override
        public void validate(Object target, Errors errors) {
            // Your custom validation logic here
        }
    }
    
  3. Custom form validation in Spring MVC:

    Custom form validation in Spring MVC involves associating your custom validator with your form using the @Validated annotation on the controller method parameter.

    @PostMapping("/submit")
    public String submitForm(@Validated YourForm form, BindingResult result) {
        if (result.hasErrors()) {
            // Handle validation errors
            return "errorPage";
        }
        // Process the form
        return "successPage";
    }
    
  4. Spring MVC custom validation messages:

    Spring MVC allows you to customize validation error messages. You can provide messages in a messages.properties file and reference them in your validation annotations.

    @CustomValidation(message = "{custom.validation.error}")
    private String customField;
    

    In messages.properties:

    custom.validation.error=Your custom validation error message.