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

Java tutorial

Introduction

Here is the source code for org.opentestsystem.delivery.testreg.domain.constraintvalidators.DateFormatValidator.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 javax.validation.ConstraintValidatorContext;

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

public class DateFormatValidator extends AbstractVetoingConstraint<DateFormat> {

    String datePattern = null;

    @Override
    public void initialize(final DateFormat constraintAnnotation) {
        this.datePattern = constraintAnnotation.datePattern();
    }

    @Override
    public boolean processValidateWithVetoing(final String value, final ConstraintValidatorContext context) {
        try {
            final DateTimeFormatter dateFormat = DateTimeFormat.forPattern(this.datePattern);
            final DateTime date = dateFormat.parseDateTime(value);
            // check if year is 4 digits
            if (String.valueOf(date.getYear()).length() != 4) {
                return false;
            }
        } catch (final IllegalArgumentException e) {
            return false;
        }
        return true;
    }

}