【问题标题】:Custom validation of Map<Locale, String> with Play Framework 1.2.5使用 Play Framework 1.2.5 自定义验证 Map<Locale, String>
【发布时间】:2013-03-19 13:45:34
【问题描述】:

我使用 Play Framework 1.2.5 并在一定程度上使用自定义验证。我不太清楚如何验证地图并报告每个字段的错误。

我的实体有一个描述属性,允许用户将描述翻译成任意数量的语言。

public class MyEntity extends Model {
    ...

    @Valid
    public Map<Locale, String> description;

    ...
}

基本上我的表单包含每个语言环境的文本区域。

<textarea rows="3" name="entity.description[en]" id="entity_description_en"></textarea>
<textarea rows="3" name="entity.description[da]" id="entity_description_da"></textarea>

我可以让它绑定,但我如何验证各个翻译,并报告字段级别的任何错误,而不仅仅是 entity.description?

更新: 我知道它可以作为控制器的一部分来完成,如下所示,但我希望所有验证都只在模型上。

public static void create(@Valid MyEntity entity) {
    validateMapKey("entity.description", entity.description, Locale.ENGLISH);
    validateMapKey("entity.description", entity.description, new Locale("da"));

    if(validation.hasErrors()) {
        params.flash(); // add http parameters to the flash scope
        validation.keep(); // keep the errors for the next request
        index();
    }

    ...     
}

private static void validateMapKey(String f, Map<Locale, ? extends Object> v, Locale l) {
    validation.required(String.format("%s[%s]", f, l), v.get(l));
}

【问题讨论】:

    标签: validation playframework-1.x


    【解决方案1】:

    @CheckWith注解可以帮到你..

    @CheckWith(MyMapCheck.class)
    public Map<Locale, String> description;
    
    static class MyMapCheck extends Check {
    
        public boolean isSatisfied(Object myEntityInstance, Object descriptionValue) {
            return checkMyDescriptionAndReturnBoolean(description);
        }
    }
    

    【讨论】:

    • 是的,我知道@CheckWith。但是如何在 entity.description[en] 上报告错误?在我看来,错误是以这种方式在 entity.description 上报告的,我无法弄清楚如何在 Check 中访问“entity.description”-context。
    • 只是你不能。因为description 正在验证不是“描述图上的值”。您可以使用 localetext 字段将 description 作为单独的实体。所以比检查text 和它的locale
    • 好的。我看了很多次,你证实了我的观察。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    相关资源
    最近更新 更多