dependsOn: Constraint para dependência entre campos
12/02/2011 00:00
package com.minhaapp.constraints
import java.util.Map;
import org.codehaus.groovy.grails.validation.AbstractConstraint
import org.springframework.validation.Errors
class DependsOnConstraint extends AbstractConstraint {
private static final String DEFAULT_MESSAGE_CODE = "default.dependson.null.message";
public static final String DEPENDS_ON_CONSTRAINT = "dependsOn";
private String field = null;
private String errorMessageCode = null;
public void setParameter(Object constraintParameter) {
if(!(constraintParameter instanceof Map))
throw new IllegalArgumentException("Parameter for constraint ["
+DEPENDS_ON_CONSTRAINT+"] of property ["
+constraintPropertyName+"] of class ["
+constraintOwningClass+"] must be a map with keys 'field' and 'errorMessageCode'");
this.field = constraintParameter.get('field', null)
this.errorMessageCode = constraintParameter.get('errorMessageCode', null)
super.setParameter(constraintParameter);
}
protected void processValidate(Object target, Object propertyValue, Errors errors) {
if(propertyValue && !target."$field"){
constraintPropertyName = field;
def args = (Object[]) [field, constraintOwningClass,
propertyValue]
if(this.errorMessageCode){
super.rejectValue(target, errors, this.errorMessageCode,
"not." + DEPENDS_ON_CONSTRAINT, args);
}else{
super.rejectValue(target, errors, DEFAULT_MESSAGE_CODE,
"not." + DEPENDS_ON_CONSTRAINT, args);
}
}
}
boolean supports(Class type) {
// any type
return true;
}
String getName() {
return DEPENDS_ON_CONSTRAINT;
}
}
import org.codehaus.groovy.grails.validation.ConstrainedProperty;
import com.minhaapp.constraints.*;
ConstrainedProperty.registerNewConstraint(DependsOnConstraint.DEPENDS_ON_CONSTRAINT, DependsOnConstraint.class)
static constraints = {
dddTelefoneCelular(nullable:true, blank: true, size:2, dependsOn:[field:'numeroTelefoneCelular', errorMessageCode:'minhaentidade.telefone.celular.obrigatorio'])
}
minhaentidade.telefone.celular.obrigatorio=O telefone celular deve ser informado
Para se registrar, clique aqui.