p:fileUpload required=“true” and custom validator doesn't work [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-07 01:18:16

问题


Since the required attribute of <p:fileUpload> still doesn't seem to work in PrimeFaces 4.0 final, I have tried to create a custom validator as follows.

@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);      
        }
    }
}

And specified with <p:fileUpload>.

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

But the validate method was never invoked. Since I'm displaying images in <p:dataGrid>, this validation is highly required. Is there a way to validate an empty <p:fileUpload>?


回答1:


Try this

@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"));
   }
 }
}


来源:https://stackoverflow.com/questions/19925708/pfileupload-required-true-and-custom-validator-doesnt-work

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