Sunday 16 June 2019

Bean validation: Future: Element must represent a future instant, date or time.


@Future annotation used to validate the instant, date or time in the future. If you annotate any element with @Future annotation, then the annotated element must be an instant, date or time in the future. In simple terms, @Future annotation ensures that the date in the future.

Employee.java
package com.sample.model;

import java.util.Date;

import javax.validation.constraints.Future;

public class Employee {

 private int id;

 private String name;

 @Future
 public Date joinedDate;

 public Employee(int id, String name, Date joinedDate) {
  this.id = id;
  this.name = name;
  this.joinedDate = joinedDate;
 }

 public int getId() {
  return id;
 }

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

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public Date getJoinedDate() {
  return joinedDate;
 }

 public void setJoinedDate(Date joinedDate) {
  this.joinedDate = joinedDate;
 }

}


Test.java

package com.sample.test;

import java.util.Calendar;
import java.util.Date;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
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(1, "Krishna", Calendar.getInstance().getTime());
  System.out.println("Validation errors on bean emp1");
  validateBean(emp1);

  /* Setting tomorrow date to emp2 */
  Calendar c = Calendar.getInstance(); 
  c.setTime(new Date()); 
  c.add(Calendar.DATE, 1);
  
  Employee emp2 = new Employee(2, "Siva", c.getTime());
  System.out.println("Validation errors on bean emp2");
  validateBean(emp2);
 }
}

Output
************************************
joinedDate,must be a future date

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



Previous                                                 Next                                                 Home

No comments:

Post a Comment