1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
package org.apache.tapestry.form.validator; |
16 | |
|
17 | |
import org.apache.tapestry.IMarkupWriter; |
18 | |
import org.apache.tapestry.IRequestCycle; |
19 | |
import org.apache.tapestry.form.FormComponentContributorContext; |
20 | |
import org.apache.tapestry.form.IFormComponent; |
21 | |
import org.apache.tapestry.form.ValidationMessages; |
22 | |
import org.apache.tapestry.json.JSONLiteral; |
23 | |
import org.apache.tapestry.json.JSONObject; |
24 | |
import org.apache.tapestry.valid.ValidationConstants; |
25 | |
import org.apache.tapestry.valid.ValidationConstraint; |
26 | |
import org.apache.tapestry.valid.ValidationStrings; |
27 | |
import org.apache.tapestry.valid.ValidatorException; |
28 | |
|
29 | |
|
30 | |
|
31 | |
|
32 | |
|
33 | |
|
34 | |
|
35 | |
public class MaxLength extends BaseValidator |
36 | |
{ |
37 | |
private int _maxLength; |
38 | |
|
39 | |
public MaxLength() |
40 | 0 | { |
41 | |
|
42 | 0 | } |
43 | |
|
44 | |
public MaxLength(String initializer) |
45 | |
{ |
46 | 0 | super(initializer); |
47 | 0 | } |
48 | |
|
49 | |
public void setMaxLength(int maxLength) |
50 | |
{ |
51 | 0 | _maxLength = maxLength; |
52 | 0 | } |
53 | |
|
54 | |
public int getMaxLength() |
55 | |
{ |
56 | 0 | return _maxLength; |
57 | |
} |
58 | |
|
59 | |
public void validate(IFormComponent field, ValidationMessages messages, Object object) |
60 | |
throws ValidatorException |
61 | |
{ |
62 | 0 | String string = (String) object; |
63 | |
|
64 | 0 | if (string.length() > _maxLength) |
65 | 0 | throw new ValidatorException(buildMessage(messages, field), |
66 | |
ValidationConstraint.MAXIMUM_WIDTH); |
67 | 0 | } |
68 | |
|
69 | |
protected String buildMessage(ValidationMessages messages, IFormComponent field) |
70 | |
{ |
71 | 0 | return messages.formatValidationMessage( |
72 | |
getMessage(), |
73 | |
ValidationStrings.VALUE_TOO_LONG, |
74 | |
new Object[] |
75 | |
{ new Integer(_maxLength), field.getDisplayName() }); |
76 | |
} |
77 | |
|
78 | |
public void renderContribution(IMarkupWriter writer, IRequestCycle cycle, |
79 | |
FormComponentContributorContext context, IFormComponent field) |
80 | |
{ |
81 | 0 | JSONObject profile = context.getProfile(); |
82 | |
|
83 | 0 | if (!profile.has(ValidationConstants.CONSTRAINTS)) { |
84 | 0 | profile.put(ValidationConstants.CONSTRAINTS, new JSONObject()); |
85 | |
} |
86 | 0 | JSONObject cons = profile.getJSONObject(ValidationConstants.CONSTRAINTS); |
87 | |
|
88 | 0 | accumulateProperty(cons, field.getClientId(), |
89 | |
new JSONLiteral("[tapestry.form.validation.isText,{" |
90 | |
+ "maxlength:" + _maxLength + "}]")); |
91 | |
|
92 | 0 | accumulateProfileProperty(field, profile, |
93 | |
ValidationConstants.CONSTRAINTS, buildMessage(context, field)); |
94 | 0 | } |
95 | |
|
96 | |
} |