01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17: package org.apache.cocoon.forms.datatype.validationruleimpl;
18:
19: import org.apache.cocoon.forms.FormsConstants;
20: import org.apache.cocoon.forms.util.I18nMessage;
21: import org.apache.cocoon.forms.validation.ValidationError;
22: import org.apache.oro.text.regex.Pattern;
23: import org.apache.oro.text.regex.PatternMatcher;
24: import org.apache.oro.text.regex.Perl5Matcher;
25: import org.outerj.expression.ExpressionContext;
26:
27: /**
28: * Checks that a String matches a regular expression.
29: *
30: * <p>The <a href="http://jakarta.apache.org/oro/">Jakarta ORO</a> library
31: * is used as regexp engine.
32: *
33: * @version $Id: RegExpValidationRule.java 449149 2006-09-23 03:58:05Z crossley $
34: */
35: public class RegExpValidationRule extends AbstractValidationRule {
36: /** Compiled regular expression. */
37: private Pattern pattern;
38: /** Original string representation of the regexp, used for informational purposes only. */
39: private String regexp;
40:
41: public ValidationError validate(Object value,
42: ExpressionContext expressionContext) {
43: String string = (String) value;
44:
45: if (matchesRegExp(string))
46: return null;
47: else
48: return hasFailMessage() ? getFailMessage()
49: : new ValidationError(new I18nMessage(
50: "validation.string.regexp",
51: new String[] { regexp },
52: FormsConstants.I18N_CATALOGUE));
53: }
54:
55: private boolean matchesRegExp(String string) {
56: PatternMatcher matcher = new Perl5Matcher();
57: return matcher.matches(string, pattern);
58: }
59:
60: void setPattern(String regexp, Pattern pattern) {
61: this .regexp = regexp;
62: this .pattern = pattern;
63: }
64:
65: public boolean supportsType(Class clazz, boolean arrayType) {
66: return clazz.isAssignableFrom(String.class) && !arrayType;
67: }
68: }
|