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.woody.datatype.validationruleimpl;
18:
19: import org.apache.cocoon.woody.datatype.ValidationError;
20: import org.apache.cocoon.woody.util.I18nMessage;
21: import org.apache.cocoon.woody.Constants;
22: import org.outerj.expression.ExpressionContext;
23:
24: /**
25: * ValidationRule that checks that a string is an email address.
26: *
27: * @version $Id: EmailValidationRule.java 433543 2006-08-22 06:22:54Z crossley $
28: */
29: public class EmailValidationRule extends AbstractValidationRule {
30:
31: public ValidationError validate(Object value,
32: ExpressionContext expressionContext) {
33: String email = (String) value;
34:
35: if (isEmail(email))
36: return null;
37: else
38: return hasFailMessage() ? getFailMessage()
39: : new ValidationError(new I18nMessage(
40: "validation.string.invalidemail",
41: Constants.I18N_CATALOGUE));
42: }
43:
44: public boolean supportsType(Class clazz, boolean arrayType) {
45: return clazz.isAssignableFrom(String.class) && !arrayType;
46: }
47:
48: private boolean isEmail(String email) {
49: // TODO there's room for improvement here
50:
51: // check that the email address does not contain spaces
52: int space = email.indexOf(' ');
53: if (space != -1)
54: return false;
55:
56: // check that there is an @, and that there's at least one character before the @
57: int atpos = email.indexOf('@');
58: if (atpos < 1)
59: return false;
60:
61: atpos++;
62:
63: // check there's not second at
64: int anotheratpos = email.indexOf('@', atpos);
65: if (anotheratpos != -1)
66: return false;
67:
68: // check there's at least one dot after the at
69: int dotAfterAt = email.indexOf('.', atpos);
70: if (dotAfterAt == -1)
71: return false;
72:
73: return true;
74: }
75: }
|