001 // Copyright 2005 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014
015 package org.apache.tapestry.form.validator;
016
017 import org.apache.tapestry.IMarkupWriter;
018 import org.apache.tapestry.IRequestCycle;
019 import org.apache.tapestry.TapestryUtils;
020 import org.apache.tapestry.form.FormComponentContributorContext;
021 import org.apache.tapestry.form.IFormComponent;
022 import org.apache.tapestry.form.ValidationMessages;
023 import org.apache.tapestry.valid.ValidationConstraint;
024 import org.apache.tapestry.valid.ValidationStrings;
025 import org.apache.tapestry.valid.ValidatorException;
026
027 /**
028 * Expects the object to be a number, and checks that the value not smaller than a specified value.
029 *
030 * @author Howard Lewis Ship
031 * @since 4.0
032 */
033 public class Min extends BaseValidator
034 {
035 private double _min;
036
037 public Min()
038 {
039 }
040
041 public Min(String initializer)
042 {
043 super(initializer);
044 }
045
046 /**
047 * Does comparison based on the {@link Number#doubleValue()}.
048 */
049
050 public void validate(IFormComponent field, ValidationMessages messages, Object object)
051 throws ValidatorException
052 {
053 Number value = (Number) object;
054
055 if (_min > value.doubleValue())
056 throw new ValidatorException(buildMessage(messages, field),
057 ValidationConstraint.TOO_SMALL);
058 }
059
060 private String buildMessage(ValidationMessages messages, IFormComponent field)
061 {
062 return messages.formatValidationMessage(
063 getMessage(),
064 ValidationStrings.VALUE_TOO_SMALL,
065 new Object[]
066 { field.getDisplayName(), new Double(_min) });
067 }
068
069 public void renderContribution(IMarkupWriter writer, IRequestCycle cycle,
070 FormComponentContributorContext context, IFormComponent field)
071 {
072 context.includeClasspathScript("/org/apache/tapestry/form/validator/NumberValidator.js");
073
074 String message = buildMessage(context, field);
075
076 StringBuffer buffer = new StringBuffer("function(event) { Tapestry.validate_min_number(event, '");
077 buffer.append(field.getClientId());
078 buffer.append("', ");
079 buffer.append(_min);
080 buffer.append(", ");
081 buffer.append(TapestryUtils.enquote(message));
082 buffer.append("); }");
083
084 context.addSubmitHandler(buffer.toString());
085 }
086
087 public void setMin(double min)
088 {
089 _min = min;
090 }
091
092 }