1 15 package org.apache.tapestry.valid; 16 17 import java.util.HashMap ; 18 import java.util.Map ; 19 20 import org.apache.tapestry.IMarkupWriter; 21 import org.apache.tapestry.IRequestCycle; 22 import org.apache.tapestry.form.IFormComponent; 23 24 29 public class IntValidator extends AbstractNumericValidator 30 { 31 private boolean _minimumSet; 32 33 private int _minimum; 34 35 private boolean _maximumSet; 36 37 private int _maximum; 38 39 public IntValidator() 40 { 41 } 42 43 public IntValidator(String initializer) 44 { 45 super(initializer); 46 } 47 48 public String toString(IFormComponent field, Object value) 49 { 50 if (value == null) 51 return null; 52 53 56 Number number = (Number ) value; 57 58 if (getZeroIsNull() && number.intValue() == 0) 59 return null; 60 61 return number.toString(); 62 } 63 64 public Object toObject(IFormComponent field, String value) throws ValidatorException 65 { 66 if (checkRequired(field, value)) 67 return null; 68 69 try 70 { 71 int intValue = Integer.parseInt(value); 72 73 if (_minimumSet && intValue < _minimum) 74 throw new ValidatorException(buildNumberTooSmallMessage( 75 field, 76 new Integer (_minimum)), ValidationConstraint.TOO_SMALL); 77 78 if (_maximumSet && intValue > _maximum) 79 throw new ValidatorException(buildNumberTooLargeMessage( 80 field, 81 new Integer (_maximum)), ValidationConstraint.TOO_LARGE); 82 83 return new Integer (intValue); 84 } 85 catch (NumberFormatException ex) 86 { 87 throw new ValidatorException(buildInvalidNumericFormatMessage(field), 88 ValidationConstraint.NUMBER_FORMAT); 89 } 90 } 91 92 public void renderValidatorContribution(IFormComponent field, IMarkupWriter writer, 93 IRequestCycle cycle) 94 { 95 if (!isClientScriptingEnabled()) 96 return; 97 98 if (!(isRequired() || _minimumSet || _maximumSet)) 99 return; 100 101 Map symbols = buildSymbols(field); 102 103 processValidatorScript(getScriptPath(), cycle, field, symbols); 104 } 105 106 Map buildSymbols(IFormComponent field) 107 { 108 Map symbols = new HashMap (); 109 110 if (isRequired()) 111 symbols.put("requiredMessage", buildRequiredMessage(field)); 112 113 symbols.put("formatMessage", buildInvalidIntegerFormatMessage(field)); 114 115 if (_minimumSet || _maximumSet) 116 { 117 Number minimum = _minimumSet ? new Integer (_minimum) : null; 118 Number maximum = _maximumSet ? new Integer (_maximum) : null; 119 120 symbols.put("minimum", minimum); 121 symbols.put("maximum", maximum); 122 123 symbols.put("rangeMessage", buildRangeMessage(field, minimum, maximum)); 124 } 125 126 return symbols; 127 } 128 129 public void setMaximum(int maximum) 130 { 131 _maximum = maximum; 132 _maximumSet = true; 133 } 134 135 public void setMinimum(int minimum) 136 { 137 _minimum = minimum; 138 _minimumSet = true; 139 } 140 141 protected String getDefaultScriptPath() 142 { 143 return "/org/apache/tapestry/valid/IntegerValidator.script"; 144 } 145 } | Popular Tags |