KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > forms > validation > impl > ValidationRuleValidator


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.validation.impl;
17
18 import org.apache.cocoon.forms.datatype.ValidationRule;
19 import org.apache.cocoon.forms.formmodel.ExpressionContextImpl;
20 import org.apache.cocoon.forms.formmodel.Widget;
21 import org.apache.cocoon.forms.validation.ValidationError;
22 import org.apache.cocoon.forms.validation.ValidationErrorAware;
23 import org.apache.cocoon.forms.validation.WidgetValidator;
24
25 /**
26  * An adapter to transform a {@link org.apache.cocoon.forms.datatype.ValidationRule} into a
27  * {@link org.apache.cocoon.forms.validation.WidgetValidator}.
28  *
29  * @author <a HREF="http://www.apache.org/~sylvain/">Sylvain Wallez</a>
30  * @version $Id: ValidationRuleValidator.java 151179 2005-02-03 16:55:16Z tim $
31  */

32 public class ValidationRuleValidator implements WidgetValidator {
33     
34     private ValidationRule rule;
35     
36     public ValidationRuleValidator(ValidationRule rule) {
37         this.rule = rule;
38     }
39
40     public boolean validate(Widget widget)
41     {
42         if (! (widget instanceof ValidationErrorAware)) {
43             // Invalid widget type
44
throw new IllegalArgumentException JavaDoc("Widget '" + widget.getRequestParameterName() + "' is not ValidationErrorAware");
45         }
46
47         Object JavaDoc value = widget.getValue();
48         if (value == null) {
49             // No value. Consider it as correct (required="true" will set an error if present)
50
return true;
51             
52         } else {
53             // Non-null value: perform validation
54
ValidationError error = this.rule.validate(value, new ExpressionContextImpl(widget));
55             if (error != null) {
56                 // Validation failed
57
((ValidationErrorAware)widget).setValidationError(error);
58                 return false;
59             } else {
60                 // Validation succeeded
61
return true;
62             }
63         }
64     }
65 }
66
Popular Tags