spring 自定义弹簧验证错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4805168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:17:39  来源:igfitidea点击:

Customize spring validation error

springvalidationcustomizationbean-validation

提问by Roberto de Santis

I want customize the spring validation error for

我想自定义弹簧验证错误

    @NotNull
    @Length(max = 80)
    private String email; 

but I'm unable to do it. What are the step to follow?

但我做不到。要遵循的步骤是什么?

回答by Chin Huang

The JSR 303 default message interpolation algorithmallows you to customize messages by supplying a resource bundle named ValidationMessages. Create a ValidationMessages.propertiesfile in the classpath containing:

JSR 303的默认邮件插补算法,您可以通过提供捆绑命名ValidationMessages的资源来定制信息。ValidationMessages.properties在类路径中创建一个文件,其中包含:

javax.validation.constraints.NotNull.message=CUSTOM NOT NULL MESSAGE
javax.validation.constraints.Size.message=CUSTOM SIZE MESSAGE

This changes the default message for the @Sizeconstraint, so you should use the @Sizeconstraint instead of the Hibernate-specific @Lengthconstraint.

这会更改@Size约束的默认消息,因此您应该使用@Size约束而不是特定于 Hibernate 的@Length约束。

Instead of changing the default message for all constraints, you can change the message for a specific constraint instance. Set the messageattribute on the constraint:

您可以更改特定约束实例的消息,而不是更改所有约束的默认消息。message在约束上设置属性:

@NotNull(message = "{email.notnull}")
private String email;

And add the message to the ValidationMessages.propertiesfile:

并将消息添加到ValidationMessages.properties文件中:

email.notnull=E-mail address is required

回答by Pushkar

By Spring I am assuming you mean Spring MVC.

通过 Spring,我假设您指的是 Spring MVC。

From the below reference http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html

从下面的参考 http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html

Here you go -

干得好 -

You create a validator class -

您创建一个验证器类 -

public class UserValidator implements Validator {

    public boolean supports(Class candidate) {
        return User.class.isAssignableFrom(candidate);
    }

    public void validate(Object obj, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "required", "Field is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "required", "Field is required.");
    }
}

Put in any validation text you want in the above field.

在上述字段中输入您想要的任何验证文本。

In the JSP you will need the following tag -

在 JSP 中,您将需要以下标记 -

<tr>
    <td>First Name:</td>
    <td><form:input path="firstName" /></td>
    <!-- Show errors for firstName field -->
    <td><form:errors path="firstName" /></td>
</tr>

This way any validation error for firstNamewill be printed.

这样,任何验证错误firstName都会被打印出来。