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  	private final Pattern pattern;
18  
19  	public RegexpValidator(final String regex) {
20  		this(regex, "valid.regexp");
21  	}
22  
23  	public RegexpValidator(final String regex, final String messageKey) {
24  		this.pattern = Pattern.compile(regex);
25  		this.setMessageKey(messageKey);
26  	}
27  
28  	public String validate(final ValidationContext ctx) {
29  		final Object value = ctx.getValue();
30  		if (value == null) {
31  			return null;
32  		}
33  		if (value instanceof String) {
34  			String stringValue = (String) value;
35  			if (StringUtil.isEmpty(stringValue)) {
36  				return null;
37  			}
38  			Matcher matcher = pattern.matcher(stringValue);
39  			if (matcher.matches()) {
40  				return null;
41  			}
42  		}
43  		return getMessage(getPropertyMessage(ctx.getName()));
44  	}
45  
46  }