英文:
Spring MVC Validation shows multiple error messages
问题
以下是您要求的翻译内容:
在尝试在Spring MVC中执行验证时,我遇到了一些问题。以下是我的验证器类:
@Component
public class LossOfCardValidator implements Validator {
public boolean supports(Class clazz) {
return SingleReplacementForm.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
SingleReplacementForm p = (SingleReplacementForm) obj;
// 检查是否为空
ValidationUtils.rejectIfEmpty(e, "contactNumber", "NotNull.contactNumber");
// 检查是否为整数
if (!p.getContactNumber().matches("[0-9]+")) {
e.rejectValue("contactNumber", "Format.contactNumber");
}
}
}
在我的Controller中,我使用以下代码进行调用:
LossOfCardValidator validator = new LossOfCardValidator();
validator.validate(singleReplacementForm, bindingResult);
它执行了验证。然而,如果我不输入联系电话字段的任何内容,在事件中将显示两条错误消息。是否有方法可以修改它,使其首先检查字段是否为空,如果不是,然后继续检查格式,以便每次只显示一条错误消息?
谢谢!
英文:
I was having some problem when trying to perform validation in Spring MVC. Here is my validator class:
@Component
public class LossOfCardValidator implements Validator {
public boolean supports(Class clazz) {
return SingleReplacementForm.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
SingleReplacementForm p = (SingleReplacementForm) obj;
// check empty
ValidationUtils.rejectIfEmpty(e, "contactNumber", "NotNull.contactNumber");
// check integer
if (!p.getContactNumber().matches("[0-9]+")) {
e.rejectValue("contactNumber", "Format.contactNumber");
}
}
In my Controller, I am calling it using this:
LossOfCardValidator validator = new LossOfCardValidator ();
validator.validate(singleReplacementForm, bindingResult);
It did performed the validation. However, in the event whereby I do not enter anything for contact number field, the two error messages will be shown. Is there anyway to modify it such that, first it will check if the field is empty, if not then proceed to check the format so that every time, there will only be one error message shown?
Thanks!
答案1
得分: 0
你可以在 Error error
对象上使用 getFieldErrorCount 方法来检查 contactNumber
字段是否已经存在错误。就像这样:
// 检查整数
if (e.getFieldErrorCount("contactNumber") <= 0 && !p.getContactNumber().matches("[0-9]+")) {
e.rejectValue("contactNumber", "Format.contactNumber");
}
这是最简单的修复方式,变动最小。你肯定应该查看 @NotNull
和 @Pattern
注解验证。
英文:
You can use getFieldErrorCount method on the Error error
object to check whether there is already an error on the contactNumber
field. Like this:
// check integer
if (e.getFieldErrorCount("contactNumber") <= 0 && !p.getContactNumber().matches("[0-9]+")) {
e.rejectValue("contactNumber", "Format.contactNumber");
}
This is the easiest fix with the smallest change set. You should definitely look at @NotNull
and @Pattern
annotation validations.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论