Reputation: 4573
We use @Min, @Max, @NotNull etc annotations for server side validations in spring MVC.Thses annotations should be place in Model Class.suppose i want to apply such annotations when needed, i dont want to apply such annotations in Model class.
For example.
I have an class Person with properties Name,Gender,Email. If I put @NotNull annotation on email property then it will get apply globaly, if my requirment get changed like if in my system there are two persons Student and Teacher and for Teacher registration email is optional but for Student its not null then how can i achive this.
can i apply validation annotations dynamiclly in case of above example-
If UserRegistration is For Teacher Then Email is optional.
If UserRegistration is For Student Then Email is Mandatory.
Upvotes: 1
Views: 2129
Reputation: 15214
To achieve this behaviour I suggest to use groups with dynamically activation. Look at my example bellow.
Person.java
:
class Person {
@NotNull(groups = StudentChecks.class)
@Email
private email;
// other members with getters/setters
public interface StudentChecks {
}
}
In this case @NotNull
constraint will be executed only when StudentChecks
group is activated. To activate validation group by condition Spring offers special annotation @Validated
.
StudentController.java
:
@Controller
public class StudentController {
@RequestMapping(value = "/students", method = RequestMethod.POST)
public String createStudent(@Validated({Person.StudentChecks.class}) Person student, BindingResult result) {
// your code
}
}
More details you can find there:
Upvotes: 6
Reputation: 1331
This is one of the issues which is presented by using bean validation. the fact that they are in fact applied globaly.
A common issue is updating an entity whith a date that has a @before ore @after annotation resulting in an invalid update, tough in fact these shouldn't be checked anymore.
A common way to fix this issue is using DTO's or Data transfer objects, in stead of directly accepting model objects in your controller, you make a class specificly for that action( which you can reuse in other actions. This way you can also disconnect your model from what your software actualy does, and it's more secure, as spring just binds everything you throw at him. For instance if a user object has an admin flag, if this admin flag is posted and set to true, spring will just gladly fill it in your model object. Using DTO's you can just copy over the fields you need and ignore the rest.
Upvotes: 0
Reputation: 14558
You will need to implement your own validator and register it in your controller.
Upvotes: 1