问题
为FileUpload组件实现了自定义验证器,请参见代码段…
FileUploadField fileUpload = new FileUploadField("fileupload",new Model<FileUpload>());
fileUpload .add(new AbstractValidator() {
protected void onValidate(IValidatable validatable) {
FileUpload fileUpload = (FileUpload) validatable.getValue();
//validate fileUpload
}
protected String resourceKey() {
return "yourErrorKey";
}
});
但是,如果用户未选择任何要上传的文件,然后单击“提交”按钮,则附加的上传验证器将被忽略!
解
默认情况下, AbstractValidator (您的自定义验证器)将不会对null值进行验证 ,请参见源代码:
文件:AbstractValidator.java
* @see IValidator#validate(IValidatable)
*/
public final void validate(IValidatable<T> validatable)
{
if (validatable.getValue() != null || validateOnNullValue())
{
onValidate(validatable);
}
}
要修复它,只需重写validateOnNullValue()
方法,如下所示:
FileUploadField fileUpload = new FileUploadField("fileupload",new Model<FileUpload>());
fileUpload .add(new AbstractValidator() {
public boolean validateOnNullValue(){
return true;
}
protected void onValidate(IValidatable validatable) {
FileUpload fileUpload = (FileUpload) validatable.getValue();
}
protected String resourceKey() {
return "yourErrorKey";
}
});
现在,当未选择任何文件并单击“提交”按钮时,将执行验证。
翻译自: https://mkyong.com/wicket/wicket-fileupload-validator-is-not-execute/