7

由于仍然的required属性<p:fileUpload>在 PrimeFaces 4.0 final 中似乎不起作用,因此我尝试按如下方式创建自定义验证器。

@FacesValidator(value="fileUploadValidator")
public final class FileUploadValidator implements Validator
{
    @Override
    public void validate(FacesContext fc, UIComponent uic, Object o) 
    throws ValidatorException
    {
        System.out.println("fileUploadValidator called.");

        if(!(o instanceof UploadedFile))
        {
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setSummary("Error");
            message.setDetail("Required");
            throw new ValidatorException(message);      
        }
    }
}

并用<p:fileUpload>.

<p:fileUpload mode="advanced" 
              required="true"
              multiple="true"
              allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
              fileUploadListener="#{bean.fileUploadListener}">
    <f:validator validatorId="fileUploadValidator"/>
</p:fileUpload>

但是 validate 方法从未被调用过。由于我在 中显示图像<p:dataGrid>,因此非常需要此验证。有没有办法验证一个空的<p:fileUpload>

4

1 回答 1

0

尝试这个

@ManagedBean(name = "docBean")
@ViewScoped
public class DocumentBean implements Serializable
{
  private UploadedFile file;

  public void handleFileUpload(FileUploadEvent event)
  {
     uploadedFile = event.getFile();
   }

   //action
   public void viewImage()
  {
    if(uploadFile==null){
     FacesContext saveContext = FacesContext.getCurrentInstance();
     saveContext.addMessage(null, new FacesMessage("Error", "Upload file  required"));
   }
 }
}
于 2015-05-11T14:38:52.093 回答