0

当我扩展一个通用命令以重用它的自定义验证器时,我遇到了 Grails 中的命令问题。

当我清理 grails 项目时,它会丢失对扩展自定义验证器的引用。我需要在项目运行时在 CommandA 中导致语法错误并撤消该错误,以便它编译回命令。

文件:/src/groovy/app/commands/ImageCommand.groovy

class ImageCommand {
    static imageValidator = { value, command ->
        ... DO SOMETHING ...
    }
}

文件:/src/groovy/app/commands/CommandA.groovy

class CommandA extends ImageCommand {
    def file
    static constraints = {
        file nullable: true, blank: true, validator: imageValidator
    }
}

为了导致错误,我只是删除了 CommandA 的一部分:

class CommandA extends ImageCommand {
    def file
    static constraints = {
        file nullable: true, blank: 
    }
}

并撤消它以强制重新编译:

class CommandA extends ImageCommand {
    def file
    static constraints = {
        file nullable: true, blank: true, validator: imageValidator
    }
}

我该怎么办?我无法将我的 CommandA 移动到 Controller 文件,因为我在很多地方都使用它。

*使用 Grails 2.2.2

4

1 回答 1

0

您可以尝试将您的验证器移动到单独的类中,src\groovy如下所示:

class PhoneNumberConstraint extends AbstractConstraint {
    private static final String NAME = "phoneNumber";
    private static final String DEFAULT_MESSAGE_CODE = "default.phoneNumber.invalid.message";

    @Override
    protected void processValidate(Object target, Object propertyValue, Errors errors) {
        if (!isPhoneNumber(target, propertyValue)) {
            Object[] args = [constraintPropertyName, constraintOwningClass, propertyValue]
            rejectValue(target, errors, DEFAULT_MESSAGE_CODE, DEFAULT_MESSAGE_CODE, args);
        }
    }

    private boolean isPhoneNumber(Object target, Object propertyValue) {
        if(propertyValue instanceof String && ((String)propertyValue).isNumber() &&
                (((String)propertyValue).length() == 13 || ((String)propertyValue).length() == 11)) {
            return true
        }
        return false
    }


    @Override
    boolean supports(Class type) {
        return type != null && String.class.isAssignableFrom(type)
    }

    @Override
    String getName() {
        return NAME
    }
}

然后像这样注册您的验证器resources.groovy

beans = {
    ConstrainedProperty.registerNewConstraint(PhoneNumberConstraint.NAME, PhoneNumberConstraint.class);
}

它对我来说完美无瑕的命令。

于 2013-05-24T07:13:07.027 回答