JSR 303 Bean Validation in Spring

 ̄綄美尐妖づ 提交于 2019-12-03 20:25:35

You've probably fixed this by now, but to set up error messages on JSR 303 formbeans you need to add entries to your property file in the following format:

<Constraint-Name>.<formbean-name>.<attribute-name>=My Message Text

In your case that will be:

NotEmpty.loginFormBean.userId=User Id must not empty

NotEmpty.loginFormBean.password=Password must not empty

where loginFormBean is the name of your form and not the class name.

in the same message.properties file you can just add the following:

userId=User Id
password=Password

or you can use a separate file for field names and separate file for validation message codes. This will be just more readable.

Good Luck :)

For reference, just log the BeanPropertyBindingResult instance and check the log. You would find four different types property codes for each property violating validations.

Here is a sample log for reference

Field error in object 'member' on field 'name': rejected value []; codes [NotEmpty.member.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [member.name,name]; arguments []; default message [name]]; default message [may not be empty]

In above log you can find codes [NotEmpty.member.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]

When you don't configure any error codes or spring doesn't find matching code then spring brings DefaultMessageCodesResolver in action to resolve error message. Check java doc to see the format of additional error codes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!