0

I just started with the field validation of request body and have all the basic annotated validations implemented. I have a field validation dependent on other field.

This class is being used a request body.

Validation condition:

If value1.equals('OK') then value2 should match a particular regex pattern, if it doesn't match the regex pattern, then raise a validation error, saying value2 doesn't match regex pattern.

I tried to create a custom annotation, but I didn't know how to do it and how to use it

Public class test
{
    String value1;
    String value2;
}

I expect the implementation of the conditional validation for that particular case

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Randhev
  • 1
  • 1
  • 3

1 Answers1

0

There are couple of ways to validate request body , or in other words implementing server side validation. Some of them can be

  1. Use basic annotations
  2. Create custom annotations for custom validation
  3. Create custom validators for custom validation

My favorite is option 3. Therefore i will give solution below for option 3. Steps are

  1. Create your custom validator

    import org.springframework.stereotype.Component;
    import org.springframework.validation.Errors;
    import org.springframework.validation.ValidationUtils;
    import org.springframework.validation.Validator;
    
    @Component
    public class MessageValidator implements Validator {
    
    @Override
    public boolean supports(Class<?> clazz) {
        return Message.class.equals(clazz);
    }
    
    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "value1", "value1 is empty");
        ValidationUtils.rejectIfEmpty(errors, "value2", "value2 is empty");
        Message m = (Message) target; 
        if (m.getValue1().trim().equalsIgnoreCase("OK") && m.getValue2().matches(SOME_REGEX_PATTERN)) {
            errors.rejectValue("value2", "My custom validator is working");
        }
        }
      }
    
  2. Bind your custom validator in controller the model by

      public class MainSiteController
      {
      @Autowired
      private MessageValidator messageValidator;
    
      @InitBinder("message")
      protected void initMessageBinder(WebDataBinder binder) {
        binder.addValidators(messageValidator);
      }
      }
    
  3. Define your model to be valid and let controller do the job

    @PostMapping( path = "/saveMessage")
    public String saveNewMessage(@Validated Message message, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return "message";
        }
        myService.saveNewMessageModel(message);
        return "messageSaved";
    }
    
Defaulter
  • 358
  • 1
  • 4
  • 17