View Javadoc

1   package org.seasar.cubby.validator.validators;
2   
3   import java.util.regex.Matcher;
4   import java.util.regex.Pattern;
5   
6   import org.apache.commons.fileupload.FileItem;
7   import org.seasar.cubby.validator.BaseValidator;
8   import org.seasar.cubby.validator.ValidationContext;
9   
10  /**
11   * 指定された正規表現にマッチしない場合にエラーとします。
12   * @see Pattern
13   * @see Matcher
14   */
15  public class FileRegexpValidator extends BaseValidator {
16  	private final Pattern pattern;
17  
18  	public FileRegexpValidator(final String regex) {
19  		this(regex, "valid.fileRegexp");
20  	}
21  
22  	public FileRegexpValidator(final String regex, final String messageKey) {
23  		this.pattern = Pattern.compile(regex);
24  		this.setMessageKey(messageKey);
25  	}
26  
27  	public String validate(final ValidationContext ctx) {
28  		final Object value = ctx.getValue();
29  		if (value instanceof FileItem) {
30  			Matcher matcher = pattern.matcher(((FileItem) value).getName());
31  			if (matcher.matches()) {
32  				return null;
33  			}
34  			return getMessage(getPropertyMessage(ctx.getName()));
35  		}
36  		return null;
37  	}
38  }