001// Copyright 2006, 2007, 2008, 2012 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.validator;
016
017import org.apache.tapestry5.Field;
018import org.apache.tapestry5.MarkupWriter;
019import org.apache.tapestry5.ValidationException;
020import org.apache.tapestry5.ioc.MessageFormatter;
021import org.apache.tapestry5.ioc.internal.util.InternalUtils;
022import org.apache.tapestry5.services.FormSupport;
023import org.apache.tapestry5.services.javascript.DataConstants;
024import org.apache.tapestry5.services.javascript.JavaScriptSupport;
025
026/**
027 * A validator that enforces that the value is not null and not the empty string. This validator is not configurable.
028 */
029public final class Required extends AbstractValidator<Void, Object>
030{
031    public Required(JavaScriptSupport javaScriptSupport)
032    {
033        super(null, Object.class, "required", javaScriptSupport);
034    }
035
036    public void validate(Field field, Void constraintValue, MessageFormatter formatter, Object value)
037            throws ValidationException
038    {
039        if (value == null || InternalUtils.isEmptyCollection(value) || InternalUtils.isBlank(value.toString()))
040            throw new ValidationException(buildMessage(formatter, field));
041    }
042
043    private String buildMessage(MessageFormatter formatter, Field field)
044    {
045        return formatter.format(field.getLabel());
046    }
047
048    /**
049     * The exception to the rule.
050     */
051    public boolean isRequired()
052    {
053        return true;
054    }
055
056    public void render(Field field, Void constraintValue, MessageFormatter formatter, MarkupWriter writer,
057                       FormSupport formSupport)
058    {
059
060        if (formSupport.isClientValidationEnabled())
061        {
062            javaScriptSupport.require("t5/core/validation");
063
064            writer.attributes(
065                    DataConstants.VALIDATION_ATTRIBUTE, true,
066                    "data-optionality", "required",
067                    "data-required-message", buildMessage(formatter, field));
068        }
069    }
070}