01: package org.jreform.internal;
02:
03: import org.jreform.Criterion;
04:
05: /**
06: * Validator for the <tt>value</tt> attribute of an input.
07: *
08: * @author armandino (at) gmail.com
09: */
10: class ValueAttributeValidator<T> {
11: private AbstractInputControl<T> input;
12: private String errorMessage;
13:
14: ValueAttributeValidator(AbstractInputControl<T> input) {
15: this .input = input;
16: }
17:
18: ValidationResult<T> validate(String valueAttribute) {
19: boolean isValid = false;
20: T parsedValue = null;
21:
22: if (valueAttribute != null && !"".equals(valueAttribute)) {
23: parsedValue = input.getType().parseValue(valueAttribute);
24: isValid = allCriteriaSatisfied(parsedValue);
25: } else {
26: // blank input is valid if it's not required
27: isValid = !input.isRequired();
28: }
29:
30: if (!isValid && errorMessage == null)
31: errorMessage = "Invalid or missing value";
32:
33: return new ValidationResult<T>(parsedValue, isValid,
34: errorMessage);
35: }
36:
37: private boolean allCriteriaSatisfied(T parsedValue) {
38: if (parsedValue == null)
39: return false;
40:
41: Criterion<T>[] criteria = input.getCriteria();
42: for (Criterion<T> criterion : criteria) {
43: if (!criterion.isSatisfied(parsedValue)) {
44: errorMessage = criterion.getOnError();
45: return false;
46: }
47: }
48:
49: return true;
50: }
51:
52: }
|