01: /*
02: * Copyright 2003 The Apache Software Foundation.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: package velosurf.validation;
18:
19: import java.sql.SQLException;
20: import java.util.Locale;
21:
22: /**
23: * <p>A string length constraint. Syntax is:</p>
24: * <pre>
25: * <<i>column</i> min-len="<i>min</i>" max-len="<i>max</i>"/>
26: * </pre>
27: * <p>where you donnot need to specify both min-len and max-len.</p>
28: * <p></p>
29: * <p>Or:</p>
30: * <pre>
31: * <<i>column</i>>
32: * <min-len value="<i>min-value</i>" [message="<i>error-message</i>"]>
33: * <max-len value="<i>max-value</i>" [message="<i>error-message</i>"]>
34: * </<i>column</i>>
35: * </pre>
36: * <p>Note: this constraint is not meant to replace an internal SQL constraint in the database,
37: * since it cannot be made sure that complex updates will respect this constraint.</p>
38: *
39: * @author <a href="mailto:claude.brisson@gmail.com">Claude Brisson</a>
40: */
41: public class Length extends FieldConstraint {
42: /** min lmength. */
43: private int minLen = 0;
44: /** max length. */
45: private int maxLen = Integer.MAX_VALUE;
46:
47: /**
48: * Constructor.
49: * @param minLen the minimum length allowed (inclusive)
50: * @param maxLen the maximum length allowed (inclusive)
51: */
52: public Length(int minLen, int maxLen) {
53: this .minLen = minLen;
54: this .maxLen = maxLen;
55: setMessage("field {0}: value '{1}' is not of the proper length");
56: }
57:
58: /**
59: * Min length setter.
60: * @param minLen minimum length
61: */
62: public void setMinLength(int minLen) {
63: this .minLen = minLen;
64: }
65:
66: /**
67: * Maximum length setter.
68: * @param maxLen maximum length
69: */
70: public void setMaxLength(int maxLen) {
71: this .maxLen = maxLen;
72: }
73:
74: /**
75: * Validate data against this constraint.
76: * @param data data to validate
77: * @return whether data is valid
78: */
79: public boolean validate(Object data) {
80: if (data == null) {
81: return true;
82: }
83: int len = data.toString().length();
84: return len >= minLen && len <= maxLen;
85: }
86:
87: /**
88: * return a string representation for this constraint.
89: * @return string
90: */
91: public String toString() {
92: return "length "
93: + (minLen > 0 && maxLen < Integer.MAX_VALUE ? "between "
94: + minLen + " and " + maxLen
95: : minLen > 0 ? ">= " + minLen : "<=" + maxLen);
96: }
97: }
|