How to make custom annotations for validations in spring -


i have put different validations different stages. example: have student class these attributes public class student{ integer id, integer rollnumber; string name; integer age, string fathersname, string mothersname }

i have validate object before saving in database on different conditions: 1. if save draft stage id , rollnumber should mandatory, 2. if save submit stage fields should mandatory.

is there way write annotations can define these validations using @draft , @submit per annotations. example @valid(type=draft)

here go.. not tough.. share code validate string valid ip address:

you need write annotation validator , need write concrete validator implementation:

below annotation class validator can use on specific field want 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 need write concrete validator implementation 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 annotation on field :

@validip(message = "enter valid ip address") private string ip; 

not work @ bind time when spring tries map form parameters bean.

just point out, isvalid method 1 needs have logic check validity.

the initialize method 1 used perform initialization before isvalid called.

try out , if still need customized question let me know might have time write you.


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -