KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > forms > datatype > validationruleimpl > RegExpValidationRule


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.apache.cocoon.forms.datatype.validationruleimpl;
17
18 import org.apache.cocoon.forms.FormsConstants;
19 import org.apache.cocoon.forms.util.I18nMessage;
20 import org.apache.cocoon.forms.validation.ValidationError;
21 import org.apache.oro.text.regex.Pattern;
22 import org.apache.oro.text.regex.PatternMatcher;
23 import org.apache.oro.text.regex.Perl5Matcher;
24 import org.outerj.expression.ExpressionContext;
25
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 326838 2005-10-20 06:26:53Z sylvain $
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 JavaDoc regexp;
40
41     public ValidationError validate(Object JavaDoc value, ExpressionContext expressionContext) {
42         String JavaDoc string = (String JavaDoc)value;
43         
44         if(matchesRegExp(string))
45             return null;
46         else
47             return hasFailMessage() ? getFailMessage() : new ValidationError(new I18nMessage("validation.string.regexp", new String JavaDoc[] {regexp}, FormsConstants.I18N_CATALOGUE));
48     }
49     
50     private boolean matchesRegExp(String JavaDoc string) {
51         PatternMatcher matcher = new Perl5Matcher();
52         return matcher.matches(string, pattern);
53     }
54     
55     void setPattern(String JavaDoc regexp, Pattern pattern) {
56         this.regexp = regexp;
57         this.pattern = pattern;
58     }
59
60     
61     public boolean supportsType(Class JavaDoc clazz, boolean arrayType) {
62         return clazz.isAssignableFrom(String JavaDoc.class) && !arrayType;
63     }
64 }
65
Popular Tags