实体非空验证消息 [英] Entity not null validation message

查看:34
本文介绍了实体非空验证消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我的应用中有 2 个实体,如下所示.两者都不可为空.

Currently I have 2 entity's in my app like below. Both are not nullable.

@Column(name = "name", nullable = false, unique = true)
@NotNull
@NotBlank
private String name;

@Column(name = "ldap", nullable = false)
@NotNull
@NotBlank
private String ldap;

当我发布带有空值的名称或 ldap 字段的数据时,我喜欢使用字段名称显示特定的非空消息.请让我知道,如何实现这一目标?

When I post with data, either name or ldap field with null, I like to have specific not null message to be display with field name. Pls let me know, how to achieve this ?

例如

{
 "name" : "check"
}

那么,错误信息应该是 ldap 字段不应该为空

then, error message should be ldap field should not be empty

推荐答案

实现自定义消息需要几个步骤:

You need to perform few steps to achieve custom message:

  @Column
    @NotNull(message = "error.title.notnull")
    @Size(min = 1, max = 30, message = "error.title.size")
    private String title;
    @Column
    @Size(max = 100, message = "error.description.size")
    private String description;

因此,下一步是通过向 SpringValidationApplication(主类)添加一个来创建 MessageSource bean.

So, the next step is to make a MessageSource bean by adding one to SpringValidationApplication (the main class).

例如:

@Bean(name = "messageSource")
public ReloadableResourceBundleMessageSource messageSource() {
  ReloadableResourceBundleMessageSource messageBundle = new ReloadableResourceBundleMessageSource();
  messageBundle.setBasename("classpath:messages/messages");
  messageBundle.setDefaultEncoding("UTF-8");
  return messageBundle;
}

这告诉 Spring 查看以消息开头的文件的消息文件夹.

This tells Spring to look at the messages folder for files starting with messages.

接下来在 src/main/resources/messages 中添加一个名为 messages.properties 的文件:

Next add a file called messages.properties inside src/main/resources/messages:

error.title.notnull=The title is a required field
error.title.size=The title should be between 1 and 30 characters
error.description.size=The description should be limited to 100 characters.

可以在此链接上找到详细信息

这篇关于实体非空验证消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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