Reputation: 137
I have to put different validations for different stages. For example: I have a student class with these attributes public class Student{ integer id, integer rollNumber; String name; integer age, String fathersName, String mothersName }
I have to validate the object before saving in database on different conditions: 1. If save is for draft stage then only id and rollnumber should be mandatory, 2. If save is for submit stage then all fields should be mandatory.
Is there any way to write annotations where I can define these validations using @draft and @submit as per annotations. For example @valid(type=draft)
Upvotes: 1
Views: 3686
Reputation: 8096
Here you go.. This is not very tough.. I will share you the code to validate a string to be a valid IP address:
You need to write an annotation for the validator and you need to write a concrete Validator implementation:
Below is the annotation class for the validator which you can use on the specific field you want to validate:
@Target({ FIELD})
@Retention(RUNTIME)
@Constraint(validatedBy = InetAddressValidator.class)
@Documented
public @interface ValidIP {
String message() default "{ValidIP.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Now you need to write a concrete validator implementation as below:
public class InetAddressValidator implements ConstraintValidator<ValidIP, String> {
private static final Pattern IPV4_PATTERN =
Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.");
public boolean isValid(String value, ConstraintValidatorContext context) {
if (!(CommonUtility.isNullOrEmpty(value) || IPV4_PATTERN.matcher(value).matches()))
{
return false;
}
return true;
}
public void initialize(ValidIP parameters) {
}
}
You can include this annotation on a field like :
@ValidIP(message = "Enter a valid IP address")
private String ip;
Not this will work at the bind time when spring tries to map the form parameters to the bean.
Just to point that out, the isValid method is one which needs to have the logic to check for validity.
The initialize method is the one which is used to perform any initialization before the isValid is called.
Try this out and if you still need help with your customized question let me know I might have some time to write it for you.
Upvotes: 2