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 * Validates that the value, a string, is of a minimum length.
029 *
030 * @author Howard Lewis Ship
031 * @since 4.0
032 */
033 public class MinLength extends BaseValidator
034 {
035 private int _minLength;
036
037 public MinLength()
038 {
039 }
040
041 public MinLength(String initializer)
042 {
043 super(initializer);
044 }
045
046 public void setMinLength(int minLength)
047 {
048 _minLength = minLength;
049 }
050
051 public int getMinLength()
052 {
053 return _minLength;
054 }
055
056 public void validate(IFormComponent field, ValidationMessages messages, Object object)
057 throws ValidatorException
058 {
059 String string = (String) object;
060
061 if (string.length() < _minLength)
062 throw new ValidatorException(buildMessage(messages, field),
063 ValidationConstraint.MINIMUM_WIDTH);
064 }
065
066 protected String buildMessage(ValidationMessages messages, IFormComponent field)
067 {
068 return messages.formatValidationMessage(
069 getMessage(),
070 ValidationStrings.VALUE_TOO_SHORT,
071 new Object[]
072 { new Integer(_minLength), field.getDisplayName() });
073 }
074
075 public void renderContribution(IMarkupWriter writer, IRequestCycle cycle,
076 FormComponentContributorContext context, IFormComponent field)
077 {
078 context.includeClasspathScript("/org/apache/tapestry/form/validator/StringValidator.js");
079
080 StringBuffer buffer = new StringBuffer("function(event) { Tapestry.validate_min_length(event, '");
081 buffer.append(field.getClientId());
082 buffer.append("', ");
083 buffer.append(_minLength);
084 buffer.append(", ");
085 buffer.append(TapestryUtils.enquote(buildMessage(context, field)));
086 buffer.append("); }");
087
088 context.addSubmitHandler(buffer.toString());
089 }
090 }