Validate field and throw exception in JSF, but attach error message to another field?

假装没事ソ 提交于 2020-03-03 05:56:25

问题


I have some fields on my page which I want cross-validated. But I don't want error from this validation to be displayed in <h:message> for this fields.

If I add validator to any of the fields, and validator throws exception, error is displayed in <h:message> for this field. On the other hand I HAVE TO throw exception if I want to suppress page from submitting. Just displaying some error message is not enough.

So I created some hidden field on the form, and attached validator there. This validator has access to UIComponents of the fields I want to validate, so it can validate them. When validator throws exception, error shows in <h:message> for hidden field, which I can place anywhere I want.

Everything works, if I put hidden field after the fields I want to validate. (If I put it before, hidden field validation is triggered before even UIComponents of my fields are updated).

The problem is it's nasty hack :) Is there some better way to do it?


回答1:


The problem is it's nasty hack :) Is there some better way to do it?

Not for the particular functional requirement. It's very true that JSF allows very little fine grained control for cross-validation of multiple fields.

Everything works, if I put hidden field after the fields I want to validate. (If I put it before, hidden field validation is triggered before even UIComponents of my fields are updated).

Components are during validations phase processed in the order as they appear in the component tree. If you have at some point an UIInput at hands which is still to be processed yet, then you need to grab the submitted value by UIInput#getSubmittedValue(). If it is already been processed, then you need to grab the submitted (and converted and validated) value by UIInput#getValue() instead.

So, if you put the hidden field with the validator after the to-be-validated components, then you need UIInput#getValue() to grab the values. If the hidden field is put before the to-be-validated components, then you need UIInput#getSubmittedValue() to grab the values.




回答2:


i have got this code working for me:

throw new ValidatorException(new ArrayList());

no errors were displayed.



来源:https://stackoverflow.com/questions/4439716/validate-field-and-throw-exception-in-jsf-but-attach-error-message-to-another-f

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