0

Following is the validator for validating file extension

FileExtensionValidator.java

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.web.multipart.MultipartFile;

public class FileExtensionValidator implements ConstraintValidator<ValidExtension, MultipartFile> {

    @Override
    public void initialize(ValidExtension extension) {

    }

    @Override
    public boolean isValid(MultipartFile file, ConstraintValidatorContext context) {

        String extension = "";
        if (null != file) {
            extension = file.getName();
        }

        return (null != extension) && (extension.endsWith(".png") || extension.endsWith(".PNG")
                || extension.endsWith(".JPEG") || extension.endsWith(".jpeg")) ? true : false;

    }

}

here is the validation interface ValidExtension.java

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, PARAMETER, TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = FileExtensionValidator.class)
@Documented
public @interface ValidExtension {

    String message() default "Not a valid Email";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

This is the controller used

@RequestMapping(value = "/file/upload", method = POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = APPLICATION_JSON_VALUE)
    public BaseResponse uploadFile(@ValidExtension @RequestParam("file") MultipartFile file) {
        return fileStorageService.upload(file);
    }

Following was added in pom

        <dependency>
            <groupId>commons-validator</groupId>
            <artifactId>commons-validator</artifactId>
            <version>1.5.1</version>
        </dependency>

Spring version used: 4

I do get get my method ever in the validation logic. Please let me understand if I am missing any basic step. Already checked the basic tutorials all say the same steps.

Thanks in advance.

Sanyam Goel
  • 2,138
  • 22
  • 40

1 Answers1

0

This might not help the person who originally created this post, but might be useful to some people like me, who was facing the same issue.

That is because you need to specify that method is going to be "validated". To do so and in order for it work:

@Valid
@PostMapping("")
fun createStudent( @ValidStudent @RequestBody dto: StudentDTO ) =
    studentService.createStudent(dto)

Then you'd manage your exception in a ControllerAdvice handling MethodArgumentNotValidException

If you want to take more control the exception throwing part (which I recommend) you'd go for something like:

@PostMapping("")
fun createStudent( @Valid @ValidStudent @RequestBody dto: StudentDTO, errors: Errors) =
    if (errors.hasErrors()) throw ResourceNotFoundException(errors.allErrors[0].defaultMessage)
        else studentService.createStudent(dto)

Then you handle the exception you want with the message your custom validator as thrown.

This is written in Kotlin but in plain Java is exactly the same. Hope this helps you.

Happy coding! :)

João Rodrigues
  • 766
  • 8
  • 12