1 | |
package org.seasar.cubby.validator.validators; |
2 | |
|
3 | |
import java.text.DateFormat; |
4 | |
import java.text.ParsePosition; |
5 | |
import java.text.SimpleDateFormat; |
6 | |
import java.util.Date; |
7 | |
|
8 | |
import org.seasar.cubby.action.FormatPattern; |
9 | |
import org.seasar.cubby.validator.BaseValidator; |
10 | |
import org.seasar.cubby.validator.ValidationContext; |
11 | |
import org.seasar.framework.exception.SRuntimeException; |
12 | |
import org.seasar.framework.util.StringUtil; |
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
|
19 | |
|
20 | |
public class DateFormatValidator extends BaseValidator { |
21 | |
|
22 | |
|
23 | |
|
24 | |
|
25 | |
private final String pattern; |
26 | |
|
27 | |
|
28 | |
|
29 | |
|
30 | |
public DateFormatValidator() { |
31 | |
this(null); |
32 | |
} |
33 | |
|
34 | |
|
35 | |
|
36 | |
|
37 | |
|
38 | |
public DateFormatValidator(final String pattern) { |
39 | 1 | this(pattern, "valid.dateFormat"); |
40 | 1 | } |
41 | |
|
42 | |
|
43 | |
|
44 | |
|
45 | |
|
46 | |
|
47 | 1 | public DateFormatValidator(final String pattern, final String messageKey) { |
48 | 1 | this.pattern = pattern; |
49 | 1 | this.setMessageKey(messageKey); |
50 | 1 | } |
51 | |
|
52 | |
public String validate(final ValidationContext ctx) { |
53 | 4 | final Object value = ctx.getValue(); |
54 | 4 | if (value == null) { |
55 | |
return null; |
56 | |
} |
57 | 4 | if (value instanceof String) { |
58 | 4 | final String stringValue = (String) value; |
59 | 4 | if (StringUtil.isEmpty((String) value)) { |
60 | |
return null; |
61 | |
} |
62 | |
try { |
63 | 4 | final DateFormat dateFormat = createDateFormat(ctx); |
64 | 4 | final ParsePosition parsePosition = new ParsePosition(0); |
65 | 4 | final Date date = dateFormat.parse(stringValue, parsePosition); |
66 | 4 | if (date != null && parsePosition.getIndex() == stringValue.length()) { |
67 | 1 | return null; |
68 | |
} |
69 | |
} catch (final Exception e) { |
70 | 3 | } |
71 | |
} |
72 | 3 | return getMessage(getPropertyMessage(ctx.getName())); |
73 | |
} |
74 | |
|
75 | |
private DateFormat createDateFormat(final ValidationContext context) { |
76 | 4 | final SimpleDateFormat dateFormat = new SimpleDateFormat(); |
77 | |
final String pattern; |
78 | 4 | if (StringUtil.isEmpty(this.pattern)) { |
79 | |
FormatPattern formatPattern = context.getFormatPattern(); |
80 | |
if (formatPattern == null) { |
81 | |
throw new SRuntimeException("ECUB0301", new Object[] { this, |
82 | |
context.getValue() }); |
83 | |
} |
84 | |
pattern = formatPattern.getDatePattern(); |
85 | |
} else { |
86 | 4 | pattern = this.pattern; |
87 | |
} |
88 | 4 | dateFormat.applyPattern(pattern); |
89 | 4 | dateFormat.setLenient(false); |
90 | 4 | return dateFormat; |
91 | |
} |
92 | |
} |