简体   繁体   English

如何在Spring的JSR 303中仅显示多行验证错误消息?

[英]How to show only one validation error message for multiple rows in JSR 303 with spring?

There is a grid which has multiple rows. 有一个具有多行的网格。 Each row has the two same text fields. 每行都有两个相同的文本字段。 I am using JSR 303 to validate these fields and the validation is happening alright. 我正在使用JSR 303来验证这些字段,并且验证正在进行中。 However the issue is that multiple error messages are being shown(one for each row) which is not desirable. 但是,问题在于显示了多个错误消息(每行一个),这是不希望的。 Is there a way to display only one error message per field for all the rows? 有没有一种方法可以针对所有行在每个字段中仅显示一条错误消息?

public ModelAndView insert(@Valid @ModelAttribute("proposalwiseselectionform")ProposalWiseSelectionForm proposalwiseselectionformobj,
                               BindingResult result,
                               HttpServletRequest request, HttpServletResponse response) {
        if (result.hasErrors()) {
            if (formBeanObj == null) {
                formBeanObj = proposalwiseselectionformobj;
            }
            mav = new ModelAndView("proposalwiseselection");

            mav.addObject("proposalwiseselectionform", formBeanObj);
        }
    }




public class ProposalWiseSelectionForm {
private String txtLineOfBusiness;
private String txtProduct;
private String btn;
private String clickedGo="N";   
private List arrLineOfBusiness=new ArrayList();
private List arrProduct=new ArrayList();
@Valid
private ArrayList documentList=initiateDocumentList();
private String txtPageMode="I";
private String enableDiscardBtn="N";
private String enableInsertBtn="N";

public ArrayList initiateDocumentList(){
    ArrayList arr=new ArrayList();
    for(int i=0; i<1;i++){
      arr.add(new ProposalWiseSelectionChildForm(i));
    }
    return arr;
  }
}



public class ProposalWiseSelectionChildForm {

private String numProposalWiseSelection;        
private String txtTransactionType;
private String txtTransactionTypeCode;  

@NotEmpty(message="Transaction Type cannot be empty")
private String txtTransactionDesc;

@NotEmpty(message="Document Type cannot be empty")
private String txtPolicyDocument;
private String ynChkBox="0";

} }

JSP snippets are as follows, JSP片段如下,

form:form action="/proposalwiseselection" commandName="proposalwiseselectionform" method="POST" id="proposalwiseselection"/  
form:errors path="*" cssClass="errorblock" element="div"/
form:input path="documentList[${docStatus.index}].txtTransactionDesc"  cssClass="noneditableinputbox" size="40" onkeydown="transactionTypeLOV(event.keyCode,this)" readonly="true" title="Press F2 to get transaction type list" /
form:hidden path="documentList[${docStatus.index}].txtTransactionTypeCode"/
form:input path="documentList[${docStatus.index}].txtPolicyDocument"  cssClass="noneditableinputbox" size="40"  readonly="true"/
form:hidden path="documentList[${docStatus.index}].numPolicyDocumentCode"/

Although the following solution is very crude, it however performs the functionality you need. 尽管以下解决方案非常粗糙,但是它可以执行所需的功能。 You can easily work make a more readable and adhere to the Spring principals, but I just whipped this up to show how something like what you are asking can be done. 您可以轻松地使工作更具可读性并遵循Spring原则,但是我只是简单地说明了如何完成您所要求的工作。

First of all you need to first obtain a Validator from Spring. 首先,您需要首先从Spring获取Validator

@Autowired
Validaror validator;

Next you need to remove the @Valid annotation and perform the validation on your own. 接下来,您需要删除@Valid批注并自行执行验证。

That means that your method would look like this: 这意味着您的方法将如下所示:

public ModelAndView insert(@ModelAttribute("proposalwiseselectionform")ProposalWiseSelectionForm proposalwiseselectionformobj,
                               BindingResult result,
                               HttpServletRequest request, HttpServletResponse response)

{
        validate(bindingResult);
        if (result.hasErrors()) {
            if (formBeanObj == null) {
                formBeanObj = proposalwiseselectionformobj;
            }
            mav = new ModelAndView("proposalwiseselection");

            mav.addObject("proposalwiseselectionform", formBeanObj);
        }
}

Finally the validate method would look like this: 最后,validate方法将如下所示:

private void validate(BindingResult bindingResult) {

    final BindingResult intermediateBindingResult = new BeanPropertyBindingResult(bindingResult.getTarget(), bindingResult.getObjectName()) ;
    validator.validate(bindingResult.getTarget(), intermediateBindingResult);

    final List<FieldError> originalFieldErrors = intermediateBindingResult.getFieldErrors();
    final Set<String> alreadyAddedFieldNames = new HashSet<>();
    final List<FieldError> distinctFieldErrors = new ArrayList<>();
    for (FieldError fieldError : originalFieldErrors) {
        if(alreadyAddedFieldNames.contains(fieldError.getField())) {
            continue;
        }

        distinctFieldErrors.add(fieldError);
        alreadyAddedFieldNames.add(fieldError.getField());
    }

    for (FieldError distinctFieldError : distinctFieldErrors) {
        bindingResult.addError(distinctFieldError);
    }
}

What the code above does is store the regular validation into an intermediate binding result, and the loop over all the FieldError and adds only the first one per field. 上面的代码所做的是将常规验证存储到中间绑定结果中,并遍历所有FieldError并在每个字段中仅添加第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM