01: /*
02: * Copyright 2006 Dan Shellman
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.iscreen.validators;
17:
18: import java.util.regex.Pattern;
19: import java.util.regex.Matcher;
20:
21: import org.iscreen.BaseValidator;
22: import org.iscreen.FailureMessage;
23: import org.iscreen.SimpleBean;
24: import org.iscreen.ValidatorContext;
25:
26: /**
27: * The RegularExpressionValidator uses a regular expression to check
28: * a single String value to ensure that it finds a match.
29: *
30: * @author Shellman, Dan
31: */
32: public class RegularExpressionValidator extends BaseValidator {
33: protected Pattern regexExp;
34: protected boolean allowNull = false;
35:
36: /**
37: * Default constructor.
38: */
39: public RegularExpressionValidator() {
40: } //end RegularExpressionValidator()
41:
42: public void validate(ValidatorContext context, Object beanToValidate) {
43: String str;
44:
45: str = getStringValue(beanToValidate);
46: if (!allowNull && str == null) {
47: context.reportFailure(getDefaultFailure());
48: } else if (str != null) {
49: Matcher matcher;
50:
51: matcher = regexExp.matcher(str);
52: if (!matcher.matches()) {
53: context.reportFailure(getDefaultFailure(), str);
54: }
55: }
56: } //end validate()
57:
58: // ***
59: // Constraints
60: // ***
61:
62: public void setRegex(String exp) {
63: regexExp = Pattern.compile(exp);
64: } //end setRegex()
65:
66: public String getRegex() {
67: return regexExp.pattern();
68: } //end getRegex()
69:
70: public void setAllowNull(boolean flag) {
71: allowNull = flag;
72: } //end setAllowNull()
73:
74: public boolean isAllowNull() {
75: return allowNull;
76: } //end isAllowNull()
77: } //end RegularExpressionValidator
|