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