001// Copyright 2007, 2008 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry5.internal.services;
016
017import org.apache.tapestry5.*;
018import org.apache.tapestry5.commons.MessageFormatter;
019import org.apache.tapestry5.services.FormSupport;
020
021public class FieldValidatorImpl implements FieldValidator
022{
023    private final Field field;
024
025    private final Object constraintValue;
026
027    private final MessageFormatter messageFormatter;
028
029    private final Validator validator;
030
031    private final FormSupport formSupport;
032
033    public FieldValidatorImpl(Field field, Object constraintValue, MessageFormatter messageFormatter,
034                              Validator validator, FormSupport formSupport)
035    {
036        this.field = field;
037        this.constraintValue = constraintValue;
038        this.messageFormatter = messageFormatter;
039        this.validator = validator;
040        this.formSupport = formSupport;
041    }
042
043    @SuppressWarnings("unchecked")
044    public void validate(Object value) throws ValidationException
045    {
046        if (!validator.isRequired() && isBlank(value)) return;
047
048        if (value != null && !validator.getValueType().isInstance(value)) return;
049
050        validator.validate(field, constraintValue, messageFormatter, value);
051    }
052
053    @SuppressWarnings("unchecked")
054    public void render(MarkupWriter writer)
055    {
056        validator.render(field, constraintValue, messageFormatter, writer, formSupport);
057    }
058
059    public boolean isRequired()
060    {
061        return validator.isRequired();
062    }
063
064    private boolean isBlank(Object value)
065    {
066        return value == null || value.equals("");
067    }
068
069}