Saturday, February 23, 2013

Validate Date from Date picker in Backing bean

Subject

Sometimes we might need to validate the date that is obtained from the date picker on the ADF screen in the backing bean.

Use-case: We might need to check if the age of the person is above 20.

Solution

Step 1:  Go to the property inspector for the text field where the date picker is used
Step 2:  Make auto-submit true
Step 3:  Enable ValueChangeListner to point to a method in a managed bean, else create a method as below


Step 4:  Use the following code to do the required validation


    public void validationMethod(ValueChangeEvent valueChangeEvent) {
        try {
            Date enteredDob = (Date)valueChangeEvent.getNewValue();

            Date currentDate = new Date();
            currentDate = (Date)currentDate.getCurrentDate();
            SimpleDateFormat displayDateFormat = new SimpleDateFormat("yyyy");
            String currentYear =
                displayDateFormat.format(currentDate.dateValue());
            String enteredYear = displayDateFormat.format(enteredDob.dateValue());

            if ((Integer.parseInt(currentYear) -
                 Integer.parseInt(enteredYear)) < 18) {
                FacesContext facesContext = FacesContext.getCurrentInstance();
                FacesMessage msg =
                    new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                     "Age must be above 20",
                                     "Age must be above 20");
                facesContext.addMessage(null, msg);
            }
        } catch (Exception nfe) {
            // TODO: Add catch code
            nfe.printStackTrace();
        }
    }
}


No comments:

Post a Comment