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  	
17  	/**
18  	 * 正規表現パターン
19  	 */
20  	private final Pattern pattern;
21  
22  	/**
23  	 * コンストラクタ
24  	 * @param regex 正規表現(例:".+\\.(png|jpg)")
25  	 */
26  	public FileRegexpValidator(final String regex) {
27  		this(regex, "valid.fileRegexp");
28  	}
29  
30  	/**
31  	 * エラーメッセージキーを指定するコンストラクタ
32  	 * @param regex 正規表現(例:".+\\.(png|jpg)")
33  	 * @param messageKey エラーメッセージキー
34  	 */
35  	public FileRegexpValidator(final String regex, final String messageKey) {
36  		this.pattern = Pattern.compile(regex);
37  		this.setMessageKey(messageKey);
38  	}
39  
40  	public String validate(final ValidationContext ctx) {
41  		final Object value = ctx.getValue();
42  		if (value instanceof FileItem) {
43  			Matcher matcher = pattern.matcher(((FileItem) value).getName());
44  			if (matcher.matches()) {
45  				return null;
46  			}
47  			return getMessage(getPropertyMessage(ctx.getName()));
48  		}
49  		return null;
50  	}
51  }