001 // Copyright 2008 The Apache Software Foundation 002 // 003 // Licensed under the Apache License, Version 2.0 (the "License"); 004 // you may not use this file except in compliance with the License. 005 // You may obtain a copy of the License at 006 // 007 // http://www.apache.org/licenses/LICENSE-2.0 008 // 009 // Unless required by applicable law or agreed to in writing, software 010 // distributed under the License is distributed on an "AS IS" BASIS, 011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 012 // See the License for the specific language governing permissions and 013 // limitations under the License. 014 015 package org.apache.tapestry5.validator; 016 017 import org.apache.tapestry5.Field; 018 import org.apache.tapestry5.MarkupWriter; 019 import org.apache.tapestry5.ValidationException; 020 import org.apache.tapestry5.ioc.MessageFormatter; 021 import org.apache.tapestry5.services.FormSupport; 022 023 import java.util.regex.Pattern; 024 025 /** 026 * A validator that checks if a given string is well-formed email address. This validator is not configurable. 027 */ 028 public class Email extends AbstractValidator<Void, String> 029 { 030 private static final String ATOM = "[^\\x00-\\x1F^\\(^\\)^\\<^\\>^\\@^\\,^\\;^\\:^\\\\^\\\"^\\.^\\[^\\]^\\s]"; 031 032 private static final String DOMAIN = "(" + ATOM + "+(\\." + ATOM + "+)*"; 033 034 private static final String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]"; 035 036 private static final Pattern PATTERN = Pattern 037 .compile("^" + ATOM + "+(\\." + ATOM + "+)*@" + DOMAIN + "|" + IP_DOMAIN + ")$", Pattern.CASE_INSENSITIVE); 038 039 public Email() 040 { 041 super(null, String.class, "invalid-email"); 042 } 043 044 public void render(Field field, Void constraintValue, MessageFormatter formatter, MarkupWriter markupWriter, 045 FormSupport formSupport) 046 { 047 } 048 049 private String buildMessage(MessageFormatter formatter, Field field) 050 { 051 return formatter.format(field.getLabel()); 052 } 053 054 public void validate(Field field, Void constraintValue, MessageFormatter formatter, String value) 055 throws ValidationException 056 { 057 if (!PATTERN.matcher(value).matches()) throw new ValidationException(buildMessage(formatter, field)); 058 } 059 }