1

我使用 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));
}
4

1 回答 1

0

@CheckWith注释可以帮助你..

@CheckWith(MyMapCheck.class)
public Map<Locale, String> description;

static class MyMapCheck extends Check {

    public boolean isSatisfied(Object myEntityInstance, Object descriptionValue) {
        return checkMyDescriptionAndReturnBoolean(description);
    }
}
于 2013-03-20T09:10:24.093 回答