1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.seasar.cubby.validator.validators;
17
18 import java.text.DateFormat;
19 import java.text.ParsePosition;
20 import java.text.SimpleDateFormat;
21 import java.util.Date;
22
23 import org.seasar.cubby.action.FormatPattern;
24 import org.seasar.cubby.controller.CubbyConfiguration;
25 import org.seasar.cubby.controller.ThreadContext;
26 import org.seasar.cubby.validator.MessageHelper;
27 import org.seasar.cubby.validator.ScalarFieldValidator;
28 import org.seasar.cubby.validator.ValidationContext;
29 import org.seasar.framework.exception.SRuntimeException;
30 import org.seasar.framework.util.StringUtil;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46 public class DateFormatValidator implements ScalarFieldValidator {
47
48
49
50
51 private final MessageHelper messageHelper;
52
53
54
55
56 private final String pattern;
57
58
59
60
61 public DateFormatValidator() {
62 this(null);
63 }
64
65
66
67
68
69
70
71 public DateFormatValidator(final String pattern) {
72 this(pattern, "valid.dateFormat");
73 }
74
75
76
77
78
79
80
81
82
83 public DateFormatValidator(final String pattern, final String messageKey) {
84 this.pattern = pattern;
85 this.messageHelper = new MessageHelper(messageKey);
86 }
87
88
89
90
91 public void validate(final ValidationContext context, final Object value) {
92 if (value == null) {
93 return;
94 }
95 if (value instanceof String) {
96 final String stringValue = (String) value;
97 if (StringUtil.isEmpty((String) value)) {
98 return;
99 }
100 try {
101 final DateFormat dateFormat = createDateFormat(context, value);
102 final ParsePosition parsePosition = new ParsePosition(0);
103 final Date date = dateFormat.parse(stringValue, parsePosition);
104 if (date != null
105 && parsePosition.getIndex() == stringValue.length()) {
106 return;
107 }
108 } catch (final Exception e) {
109 }
110 }
111
112 context.addMessageInfo(this.messageHelper.createMessageInfo());
113 }
114
115 private DateFormat createDateFormat(final ValidationContext context,
116 final Object value) {
117 final SimpleDateFormat dateFormat = new SimpleDateFormat();
118 final String pattern;
119 if (StringUtil.isEmpty(this.pattern)) {
120 final CubbyConfiguration configuration = ThreadContext
121 .getConfiguration();
122 final FormatPattern formatPattern = configuration
123 .getFormatPattern();
124 if (formatPattern == null) {
125 throw new SRuntimeException("ECUB0301", new Object[] { this,
126 value });
127 }
128 pattern = formatPattern.getDatePattern();
129 } else {
130 pattern = this.pattern;
131 }
132 dateFormat.applyPattern(pattern);
133 dateFormat.setLenient(false);
134 return dateFormat;
135 }
136
137 }