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.seasar.cubby.validator.BaseValidator;
7   import org.seasar.cubby.validator.ValidationContext;
8   import org.seasar.framework.util.StringUtil;
9   
10  /**
11   * 指定された正規表現にマッチするか検証します。
12   * @see Pattern
13   * @see Matcher
14   */
15  public class RegexpValidator extends BaseValidator {
16  
17  	/**
18  	 * 正規表現パターン
19  	 */
20  	private final Pattern pattern;
21  
22  	/**
23  	 * コンストラクタ
24  	 * @param regex 正規表現(例:".+\\.(png|jpg)")
25  	 */
26  	public RegexpValidator(final String regex) {
27  		this(regex, "valid.regexp");
28  	}
29  
30  	/**
31  	 * エラーメッセージキーを指定するコンストラクタ
32  	 * @param regex 正規表現(例:".+\\.(png|jpg)")
33  	 * @param messageKey エラーメッセージキー
34  	 */
35  	public RegexpValidator(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 == null) {
43  			return null;
44  		}
45  		if (value instanceof String) {
46  			String stringValue = (String) value;
47  			if (StringUtil.isEmpty(stringValue)) {
48  				return null;
49  			}
50  			Matcher matcher = pattern.matcher(stringValue);
51  			if (matcher.matches()) {
52  				return null;
53  			}
54  		}
55  		return getMessage(getPropertyMessage(ctx.getName()));
56  	}
57  
58  }