1

It's pretty straightforward to validate all the fields in a object by binding the object to a form and using the @Valid notation for the object in the validating controller method.

Let's say I have an update screen that only allows the user to update some of the fields. Is there away to avoid having manual validation?

Thanks!

2
  • 1
    What's the harm in letting validation run against all other fields? Whose to say that a malicious user wouldn't modify those before they made its way to the server? Commented May 10, 2017 at 21:53
  • I guess you're right! I had some imaginary harm factor in my head. Thanks! Commented May 10, 2017 at 22:16

1 Answer 1

3

To have a validation against a subset of validation rules, you can use the spring feature of validation groups with @Validated

You will have to define a set of groups for your bean or form model similar to this

public class Form {

  public interface Group1 { /*empty interface*/ };

  public interface Group2 { /*empty interface*/ };

  @NotEmpty(groups = { Group1.class }) // associate constraints
  private String field1;               // to a validation group 

  @NotEmpty(groups = { Group2.class })
  private String field2;

}

And in your controller, you can use the annotation like this

@Controller
public class FormController {

  @RequestMapping(value = "/validate1", method = RequestMethod.POST)
  public String updateGroup1(@Validated(Form.Group1.class) Form form, Errors errors) {
    if (errors.hasErrors()) {
      // return to the same view
    }
    // return success
  }

}

You can find here a good example for it

https://narmo7.wordpress.com/2014/04/26/how-to-set-up-validation-group-in-springmvc/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.