KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > woody > datatype > validationruleimpl > EmailValidationRule


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.woody.datatype.validationruleimpl;
17
18 import org.apache.cocoon.woody.datatype.ValidationError;
19 import org.apache.cocoon.woody.util.I18nMessage;
20 import org.apache.cocoon.woody.Constants;
21 import org.outerj.expression.ExpressionContext;
22
23 /**
24  * ValidationRule that checks that a string is an email address.
25  *
26  * @version $Id: EmailValidationRule.java 30932 2004-07-29 17:35:38Z vgritsenko $
27  */

28 public class EmailValidationRule extends AbstractValidationRule {
29
30     public ValidationError validate(Object JavaDoc value, ExpressionContext expressionContext) {
31         String JavaDoc email = (String JavaDoc)value;
32
33         if (isEmail(email))
34             return null;
35         else
36             return hasFailMessage() ? getFailMessage() : new ValidationError(new I18nMessage("validation.string.invalidemail", Constants.I18N_CATALOGUE));
37     }
38
39     public boolean supportsType(Class JavaDoc clazz, boolean arrayType) {
40         return clazz.isAssignableFrom(String JavaDoc.class) && !arrayType;
41     }
42
43     private boolean isEmail(String JavaDoc email) {
44         // TODO there's room for improvement here
45

46         // check that the email address does not contain spaces
47
int space = email.indexOf(' ');
48         if (space != -1)
49             return false;
50
51         // check that there is an @, and that there's at least one character before the @
52
int atpos = email.indexOf('@');
53         if (atpos < 1)
54             return false;
55
56         atpos++;
57
58         // check there's not second at
59
int anotheratpos = email.indexOf('@', atpos);
60         if (anotheratpos != -1)
61             return false;
62
63         // check there's at least one dot after the at
64
int dotAfterAt = email.indexOf('.', atpos);
65         if (dotAfterAt == -1)
66             return false;
67
68         return true;
69     }
70 }
Popular Tags