如何自定义Hibernate @Size错误消息以指示输入字段的长度 [英] How to customize Hibernate @Size error message to indicate length of entered field

查看:274
本文介绍了如何自定义Hibernate @Size错误消息以指示输入字段的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为文本字段自定义错误消息,以包含输入的实际字符数。我已经能够得到这个工作,但我不满意我的解决方案,所以我想知道其他人做了什么来完成这个。




  • Spring 4.1.2

  • Hibernate 4.3.10

  • Hibernate Validator 5.1.3



字段注解(限于10个用于测试目的 - 实际大小为150)

  @Column(name =NAME,nullable = false)
@Size(max = 10)
私人字符串名称;

message.properties

  Size.person.name =最大为{1}个字符

JSP代码

 < spring:bind path =person.name> ; 
< c:set var =nameError> $ {status.errorMessage}< / c:set>
< c:set var =nameDisplayValue> $ {status.displayValue}< / c:set>
< / spring:bind>
< c:set var =nameLen> $ {fn:length(nameDisplayValue)}< / c:set>
< c:if test =$ {nameLen gt 0}>
< / c:if>
< / c:if>

< div class =form-group col-sm-9< c:if test =$ {not empty nameError}> has-error< / c:if>> ;
< label class =control-labelid =nameLabelfor =inputName>名称:< c:if test =$ {not empty nameError}>& nbsp;& amp ; NBSP; $ {nameError}< / C:如果>< /标签>
< form:input type =textsize =10class =form-controlid =inputNameplaceholder =Namepath =nameautocomplete =off/>
< / div>

输出



这对于一个字段是可以的,但我正在处理的表单有超过10个字段有尺寸验证。此外,form:input的size =10设置实际上并没有做任何事情,即你仍然可以输入10个以上的字符。

我知道一个选择是编写一个自定义验证器,但这看起来像是我想要做的事情。另一种方法是在表单发布之前捕获错误,但我试图保留所有的验证服务器端。任何建议都将不胜感激。

解决方案

有一个关于在Hibernate文档中插入验证消息的好文档:第4章。插入约束错误信息

如果您在类路径的根目录下创建了一个文件 ValidationMessages.properties ,那么您可以更改所有验证消息there:

  javax.validation.constraints.Size.message =请输入至少{min}和至多{max}个字符。 

{...} 只是注释的属性名称。这几乎适用于每个约束。如果您想引用验证的值,可以使用 {validatedValue} 。您可以使用 Formatter 格式化值:

  .. 。$ {formatter.format('...',validatedValue)} ... 

没有 length 的格式字符串。所以如果你真的想为所有的 @Size ,那么您将必须实现您自己的 javax.validation.MessageInterpolator (请参阅上面的链接中的自定义消息插值) 。



其他说明:更改默认验证消息时会产生副作用: @Size 也可用于收藏。在这种情况下,至少我的信息是不恰当的。我通常为此创建第二个验证消息:

  javax.validation.constraints.Size.Collection.message =请至少选择{min}和至多{max}个元素。 

在约束中使用那个:

  public final class ValidationMessages {
public static final String COLLECTION_SIZE =
javax.validation.constraints.Size.Collection.message;
}

public class MyClass {
@Size(min = 1,max = 10,message = ValidationMessages.COLLECTION_SIZE)
private Collection< String>要素;



$ b $ p
$ b

在我的代码风格工具中使用匹配规则,我确保我不会忘记为集合上的 @Size 注解定义消息。


I would like to customize the error message for text fields to include the actual number of characters that were entered. I've been able to get this to work but am not satisfied with my solution, so I'm wondering what others have done to accomplish this.

  • Spring 4.1.2
  • Hibernate 4.3.10
  • Hibernate Validator 5.1.3

Field Annotation (limited to 10 for testing purposes - actual size is 150)

@Column(name = "NAME", nullable = false)
@Size(max=10)
private String name;

message.properties

Size.person.name=Maximum is {1} characters

JSP code

    <spring:bind path="person.name">
        <c:set var="nameError">${status.errorMessage}</c:set>
        <c:set var="nameDisplayValue">${status.displayValue}</c:set>
        <c:set var="nameCode">${status.errorCode}</c:set>
    </spring:bind>
    <c:if test="${fn:contains(nameCode,'Size')}">
        <c:set var="nameLen">${fn:length(nameDisplayValue)}</c:set>
        <c:if test="${nameLen gt 0}">
            <c:set var="nameError">${nameError += " (you entered " += nameLen += ")"}</c:set>  
        </c:if>
    </c:if>

    <div class="form-group col-sm-9 <c:if test="${not empty nameError}">has-error</c:if>">
        <label class="control-label" id="nameLabel" for="inputName">Name:<c:if test="${not empty nameError}">&nbsp;&nbsp;${nameError}</c:if></label>
        <form:input type="text" size="10" class="form-control" id="inputName" placeholder="Name" path="name" autocomplete="off"/>                                                           
    </div>

Output

This is ok for one field, but the form I'm working on has more than 10 fields that have size validation. Also, the size="10" setting for form:input does not appear to actually do anything, i.e., you can still enter more than 10 characters.

I know one option is to write a custom validator but that seems like overkill for what I want to do. Another would be to catch the error before the form is posted, but I'm trying to keep all of the validation server-side. Any suggestions would be greatly appreciated.

解决方案

There is a good documentation about interpolating validation messages in the Hibernate documentation: Chapter 4. Interpolating constraint error messages.

If you create a file ValidationMessages.properties in the root of your classpath then you can change all validation messages there:

javax.validation.constraints.Size.message=Please enter at least {min} and at most {max} characters.

The parameters in {...} are just the attribute names of the annotation. That works for nearly every constraint. If you want to reference the validated value, you can use {validatedValue}. You can as well use Formatter to format the value:

... ${formatter.format('...', validatedValue)} ...

Unfortunately there is no format string for length.

So if you really want to have such a message for all @Size, then you will have to implement your own javax.validation.MessageInterpolator (see Custom message interpolation in the link above).

Additional remark: There is a side effect when changing the default validation message: @Size is available for collections as well. And in that case at least my message is not appropriate. I usually create a second validation message for this:

javax.validation.constraints.Size.Collection.message=Please select at least {min} and at most {max} elements.

And use that one in the constraint:

public final class ValidationMessages {
  public static final String COLLECTION_SIZE = 
      "javax.validation.constraints.Size.Collection.message";
}

public class MyClass {
    @Size(min = 1, max = 10, message = ValidationMessages.COLLECTION_SIZE)
    private Collection<String> elements;
}

With a matching rule in my code style tool I ensure that I don't forget to define the message for @Size annotations on collections.

这篇关于如何自定义Hibernate @Size错误消息以指示输入字段的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆