Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- @Constraint(validatedBy = { FieldValidator.class })
- public @interface NotNullOn {
- String message() default "values Missing";
- Class<?>[] groups() default {};
- Class<? extends Payload>[] payload() default {};
- }
- public class FieldValidator implements ConstraintValidator<NotNullOn, Employee> {
- @Override
- public void initialize(NotNullOn constraintAnnotation) {
- //default method.
- }
- @Override
- public boolean isValid(Employee value, ConstraintValidatorContext context) {
- if (value == null){
- return false;
- }
- if (value.getLastName() == null) {
- context.disableDefaultConstraintViolation();
- context.buildConstraintViolationWithTemplate("lastName is required")
- .addPropertyNode("lastName").addConstraintViolation();
- return false;
- }
- if (value.getLastName() != null){
- context.disableDefaultConstraintViolation();
- context.buildConstraintViolationWithTemplate("lastName is required for company address")
- .addPropertyNode("lastName").addConstraintViolation();
- return false;
- }
- return true;
- }
- }
- public class Department {
- private Long deptId;
- private String deptName;
- private List<Employee> employees;
- public Long getDeptId() {
- return deptId;
- }
- public void setDeptId(Long deptId) {
- this.deptId = deptId;
- }
- public String getDeptName() {
- return deptName;
- }
- public void setDeptName(String deptName) {
- this.deptName = deptName;
- }
- public List<Employee> getEmployees() {
- return employees;
- }
- public void setEmployees(List<Employee> employees) {
- this.employees = employees;
- }
- }
- @NotNullOn
- public class Employee {
- private String name;
- private String lastName;
- private Long phNum;
- private Long empId;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getLastName() {
- return lastName;
- }
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
- public Long getPhNum() {
- return phNum;
- }
- public void setPhNum(Long phNum) {
- this.phNum = phNum;
- }
- public Long getEmpId() {
- return empId;
- }
- public void setEmpId(Long empId) {
- this.empId = empId;
- }
- }
Add Comment
Please, Sign In to add comment