001package gwt.material.design.client.base.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 gwt.material.design.client.base.validator.ValidationMessages.Keys; 024 025import java.util.Collection; 026import java.util.Map; 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 @Override 055 public int getPriority() { 056 return Priority.MEDIUM; 057 } 058 059 @Override 060 public boolean isValid(T value) { 061 int length = 0; 062 if (value instanceof Map<?, ?>) { 063 length = ((Map<?, ?>) value).size(); 064 } else if (value instanceof Collection<?>) { 065 length = ((Collection<?>) value).size(); 066 } else if (value instanceof Object[]) { 067 length = ((Object[]) value).length; 068 } else if (value != null) { 069 length = value.toString().length(); 070 } 071 return length >= minValue && length <= maxValue; 072 } 073 074 /** 075 * @param max the max to set 076 */ 077 public void setMax(Integer max) { 078 this.maxValue = max; 079 assert maxValue > 0; 080 } 081 082 /** 083 * @param min the min to set 084 */ 085 public void setMin(Integer min) { 086 minValue = min; 087 if (minValue == null || minValue < 0) { 088 minValue = 0; 089 } 090 } 091}