001package org.gwtbootstrap3.client.ui.form.validator;
002
003/*
004 * #%L
005 * GwtBootstrap3
006 * %%
007 * Copyright (C) 2015 GwtBootstrap3
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import java.util.Collection;
024import java.util.Map;
025
026import org.gwtbootstrap3.client.ui.form.validator.ValidationMessages.Keys;
027
028/**
029 * Validator for checking the length of a map, array, collection, or string value. If type is not one of the
030 * aformentioned, the {@link Object#toString()} method is called to get the string representation of the
031 * object.
032 *
033 * @param <T> the generic type
034 * @author Steven Jardine
035 */
036public class SizeValidator<T> extends AbstractValidator<T> {
037
038    private Integer maxValue;
039
040    private Integer minValue;
041
042    public SizeValidator(Integer min, Integer max) {
043        super(Keys.SIZE, new Object[] { min, max });
044        setMin(min);
045        setMax(max);
046    }
047
048    public SizeValidator(Integer min, Integer max, String invalidMessageOverride) {
049        super(invalidMessageOverride);
050        setMin(min);
051        setMax(max);
052    }
053
054    /** {@inheritDoc} */
055    @Override
056    public int getPriority() {
057        return Priority.MEDIUM;
058    }
059
060    /** {@inheritDoc} */
061    @Override
062    public boolean isValid(T value) {
063        int length = 0;
064        if (value instanceof Map<?, ?>) {
065            length = ((Map<?, ?>) value).size();
066        } else if (value instanceof Collection<?>) {
067            length = ((Collection<?>) value).size();
068        } else if (value instanceof Object[]) {
069            length = ((Object[]) value).length;
070        } else if (value != null) {
071            length = value.toString().length();
072        }
073        return length >= minValue && length <= maxValue;
074    }
075
076    /**
077     * @param max the max to set
078     */
079    public void setMax(Integer max) {
080        this.maxValue = max;
081        assert maxValue > 0;
082    }
083
084    /**
085     * @param min the min to set
086     */
087    public void setMin(Integer min) {
088        minValue = min;
089        if (minValue == null || minValue < 0) {
090            minValue = 0;
091        }
092    }
093
094}