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 015package org.apache.tapestry.form.validator; 016 017import org.apache.tapestry.IMarkupWriter; 018import org.apache.tapestry.IRequestCycle; 019import org.apache.tapestry.TapestryUtils; 020import org.apache.tapestry.form.FormComponentContributorContext; 021import org.apache.tapestry.form.IFormComponent; 022import org.apache.tapestry.form.ValidationMessages; 023import org.apache.tapestry.valid.ValidationConstraint; 024import org.apache.tapestry.valid.ValidationStrings; 025import org.apache.tapestry.valid.ValidatorException; 026 027/** 028 * Validates that the input value is not larger than a particular maximum value. 029 * 030 * @author Howard Lewis Ship 031 * @since 4.0 032 */ 033public class Max extends BaseValidator 034{ 035 private double _max; 036 037 public Max() 038 { 039 } 040 041 public Max(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 (value.doubleValue() > _max) 056 throw new ValidatorException(buildMessage(messages, field), 057 ValidationConstraint.TOO_LARGE); 058 } 059 060 private String buildMessage(ValidationMessages messages, IFormComponent field) 061 { 062 return messages.formatValidationMessage( 063 getMessage(), 064 ValidationStrings.VALUE_TOO_LARGE, 065 new Object[] 066 { field.getDisplayName(), new Double(_max) }); 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 = TapestryUtils.enquote(buildMessage(context, field)); 075 076 StringBuffer buffer = new StringBuffer("function(event) { Tapestry.validate_max_number(event, '"); 077 buffer.append(field.getClientId()); 078 buffer.append("', "); 079 buffer.append(_max); 080 buffer.append(", "); 081 buffer.append(message); 082 buffer.append("); }"); 083 084 context.addSubmitHandler(buffer.toString()); 085 } 086 087 public void setMax(double max) 088 { 089 _max = max; 090 } 091 092}