org.opentestsystem.delivery.testreg.domain.constraintvalidators.BirthDateFormatValidator.java Source code

Java tutorial

Introduction

Here is the source code for org.opentestsystem.delivery.testreg.domain.constraintvalidators.BirthDateFormatValidator.java

Source

/*******************************************************************************
 * Educational Online Test Delivery System
 * Copyright (c) 2013 American Institutes for Research
 * 
 * Distributed under the AIR Open Source License, Version 1.0
 * See accompanying file AIR-License-1_0.txt or at
 * http://www.smarterapp.org/documents/American_Institutes_for_Research_Open_Source_Software_License.pdf
 ******************************************************************************/

package org.opentestsystem.delivery.testreg.domain.constraintvalidators;

import org.joda.time.DateTime;
import org.joda.time.IllegalFieldValueException;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.opentestsystem.delivery.testreg.domain.constraints.BirthDateFormat;

import javax.validation.ConstraintValidatorContext;

public class BirthDateFormatValidator extends AbstractVetoingConstraint<BirthDateFormat> {

    String datePattern = null;

    @Override
    public void initialize(BirthDateFormat constraintAnnotation) {
        datePattern = constraintAnnotation.datePattern();
    }

    @Override
    public boolean processValidateWithVetoing(String value, ConstraintValidatorContext context) {
        try {
            DateTimeFormatter dateFormat = DateTimeFormat.forPattern(datePattern);
            DateTime date = dateFormat.parseDateTime(value);
            String[] values = value.split("-");
            // check if year is 4 digits, month is 2 digits and day is 2 digits
            if (values[0].length() != 4 || values[1].length() != 2 || values[2].length() != 2) {
                return false;
            }
            if (date.getYear() < 0 || date.getYear() > 9999) {
                return false;
            }
        } catch (IllegalFieldValueException ifve) {
            return false;
        } catch (IllegalArgumentException iae) {
            return false;
        }
        return true;
    }

}