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 java.util.regex.Matcher;
20: import java.util.regex.Pattern;
21:
22: import org.apache.tapestry.Field;
23: import org.apache.tapestry.MarkupWriter;
24: import org.apache.tapestry.PageRenderSupport;
25: import org.apache.tapestry.ValidationException;
26: import org.apache.tapestry.Validator;
27: import org.apache.tapestry.ioc.MessageFormatter;
28:
29: public class Regexp implements Validator<Pattern, String> {
30: public Class<Pattern> getConstraintType() {
31: return Pattern.class;
32: }
33:
34: public String getMessageKey() {
35: return "regexp";
36: }
37:
38: public Class<String> getValueType() {
39: return String.class;
40: }
41:
42: public boolean invokeIfBlank() {
43: return false;
44: }
45:
46: private String buildMessage(MessageFormatter formatter,
47: Field field, Pattern constraintValue) {
48: return formatter.format(constraintValue.toString(), field
49: .getLabel());
50: }
51:
52: public void render(Field field, Pattern constraintValue,
53: MessageFormatter formatter, MarkupWriter writer,
54: PageRenderSupport pageRenderSupport) {
55: pageRenderSupport.addScript(
56: "Tapestry.Field.regexp('%s', %s, %s);", field
57: .getClientId(),
58: quote(constraintValue.pattern()), quote(buildMessage(
59: formatter, field, constraintValue)));
60:
61: }
62:
63: public void validate(Field field, Pattern constraintValue,
64: MessageFormatter formatter, String value)
65: throws ValidationException {
66: Matcher matcher = constraintValue.matcher(value);
67:
68: if (!matcher.matches())
69: throw new ValidationException(buildMessage(formatter,
70: field, constraintValue));
71: }
72:
73: }
|