01: // Copyright 2007 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.tapestry.validator;
16:
17: import static org.apache.tapestry.TapestryUtils.quote;
18:
19: import org.apache.tapestry.Field;
20: import org.apache.tapestry.MarkupWriter;
21: import org.apache.tapestry.PageRenderSupport;
22: import org.apache.tapestry.ValidationException;
23: import org.apache.tapestry.Validator;
24: import org.apache.tapestry.ioc.MessageFormatter;
25:
26: public final class MaxLength implements Validator<Integer, String> {
27: public Class<Integer> getConstraintType() {
28: return Integer.class;
29: }
30:
31: public String getMessageKey() {
32: return "maximum-string-length";
33: }
34:
35: public Class<String> getValueType() {
36: return String.class;
37: }
38:
39: public boolean invokeIfBlank() {
40: return false;
41: }
42:
43: public void validate(Field field, Integer constraintValue,
44: MessageFormatter formatter, String value)
45: throws ValidationException {
46: if (value.length() > constraintValue)
47: throw new ValidationException(buildMessage(formatter,
48: field, constraintValue));
49: }
50:
51: private String buildMessage(MessageFormatter formatter,
52: Field field, Integer constraintValue) {
53: return formatter.format(constraintValue, field.getLabel());
54: }
55:
56: public void render(Field field, Integer constraintValue,
57: MessageFormatter formatter, MarkupWriter writer,
58: PageRenderSupport pageRenderSupport) {
59: // TODO: write a maxlength attribute into the element? But that's only for
60: // textfield, not for textarea.
61:
62: pageRenderSupport.addScript(
63: "Tapestry.Field.maxlength('%s', %d, %s);", field
64: .getClientId(), constraintValue,
65: quote(buildMessage(formatter, field, constraintValue)));
66: }
67: }
|