Sunday, 16 June 2019

Bean Validation: @AssertFalse: Validate falsity of the element

If you annotate any element with @AssertFalse annotation, then the annotated element must be false.

Supported Types
a.   boolean
b.   Boolean

Where can I apply this annotation?
a.   METHOD,
b.   FIELD,
c.    ANNOTATION_TYPE,
d.   CONSTRUCTOR,
e.   PARAMETER,
f.     TYPE_USE

Employee.java
package com.sample.model;

import javax.validation.constraints.AssertFalse;

public class Employee {

 private int id;

 @AssertFalse
 private boolean isExperienced;

 public Employee(int id, boolean isExperienced) {
  this.id = id;
  this.isExperienced = isExperienced;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public boolean isExperienced() {
  return isExperienced;
 }

 public void setExperienced(boolean isExperienced) {
  this.isExperienced = isExperienced;
 }

}


Test.java

package com.sample.test;

import java.util.Set;

import javax.validation.*;
import javax.validation.ValidatorFactory;

import com.sample.model.Employee;

public class Test {
 private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
 private static Validator validator = validatorFactory.getValidator();

 private static void validateBean(Employee emp) {
  System.out.println("************************************");
  Set<ConstraintViolation<Employee>> validationErrors = validator.validate(emp);

  if (validationErrors.size() == 0) {
   System.out.println("No validation errors....");
  }

  for (ConstraintViolation<Employee> violation : validationErrors) {
   System.out.println(violation.getPropertyPath() + "," + violation.getMessage());
  }
  System.out.println("");
 }

 public static void main(String args[]) {

  Employee emp1 = new Employee(123, false);
  System.out.println("Validation errors on bean emp1");
  validateBean(emp1);

  Employee emp2 = new Employee(234, true);
  System.out.println("Validation errors on bean emp2");
  validateBean(emp2);
 }
}


Run above application, you can able to see below output in the console.

Validation errors on bean emp1
************************************
No validation errors....

Validation errors on bean emp2
************************************
isExperienced,must be false



Previous                                                 Next                                                 Home

No comments:

Post a Comment