java - Validate Bean inside a Bean -
i have following beans
public class mymodel { @notnull @notempty private string name; @notnull @notempty private int age; //how validate this? private mysubmodel submodel; } public class mysubmodel{ private string subname; }
then use @valid annotation validate controller side.
thank you
you can define own custom validation bean validation (jsr-303), example here simple custom zip code validation, annotating custom annotation can validate:
@documented @constraint(validatedby = zipcodevalidator.class) @target(elementtype.field) @retention(retentionpolicy.runtime) public @interface zipcode { string message() default "zip code must 5 numeric characters"; class<?>[] groups() default {}; class<?>[] payload() default {}; }
and custom validation class, instead of , can use custom beans <yourannotationclassname,typewhichisbeingvalidated>
public class zipcodevalidator implements constraintvalidator<zipcode, string> { @override public void initialize(zipcode zipcode) { } @override public boolean isvalid(string string, constraintvalidatorcontext context) { if (string.length() != 5) return false; (char c : string.tochararray()) { if (!character.isdigit(c)) return false; } return true; } }
and here usage of it:
public class address{ @zipcode private string zip; }
Comments
Post a Comment