1 /* Copyright 2004-2005 Graeme Rocher
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
15 package org
.codehaus
.groovy
.grails
.validation
;
17 import org
.apache
.commons
.lang
.StringUtils
;
18 import org
.apache
.commons
.validator
.EmailValidator
;
19 import org
.springframework
.validation
.Errors
;
22 * A Constraint that validates an email address
24 * @author Graeme Rocher
27 * Created: Jan 19, 2007
30 class EmailConstraint
extends AbstractConstraint
{
32 private boolean email
;
36 * @see org.codehaus.groovy.grails.validation.Constraint#supports(java.lang.Class)
38 public boolean supports(Class type
) {
39 return type
!= null && String
.class.isAssignableFrom(type
);
43 * @see org.codehaus.groovy.grails.validation.ConstrainedProperty.AbstractConstraint#setParameter(java.lang.Object)
45 public void setParameter(Object constraintParameter
) {
46 if(!(constraintParameter
instanceof Boolean
))
47 throw new IllegalArgumentException("Parameter for constraint ["+ConstrainedProperty
.EMAIL_CONSTRAINT
+"] of property ["+constraintPropertyName
+"] of class ["+constraintOwningClass
+"] must be a boolean value");
49 this.email
= ((Boolean
)constraintParameter
).booleanValue();
50 super.setParameter(constraintParameter
);
53 public String
getName() {
54 return ConstrainedProperty
.EMAIL_CONSTRAINT
;
57 protected void processValidate(Object target
, Object propertyValue
, Errors errors
) {
59 EmailValidator emailValidator
= EmailValidator
.getInstance();
60 Object
[] args
= new Object
[] { constraintPropertyName
, constraintOwningClass
, propertyValue
};
61 String value
= propertyValue
.toString();
62 if(StringUtils
.isBlank(value
))return;
63 if(!emailValidator
.isValid(value
) ) {
64 super.rejectValue(target
,errors
,ConstrainedProperty
.DEFAULT_INVALID_EMAIL_MESSAGE_CODE
,ConstrainedProperty
.EMAIL_CONSTRAINT
+ ConstrainedProperty
.INVALID_SUFFIX
,args
);