p:fileUpload required ="true";和自定义验证器不起作用 [英] p:fileUpload required="true" and custom validator doesn't work

查看:333
本文介绍了p:fileUpload required ="true";和自定义验证器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于<p:fileUpload>required属性在PrimeFaces 4.0 final中似乎仍然不起作用,因此我尝试创建一个自定义验证器,如下所示.

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

并用<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>?

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>?

推荐答案

尝试一下

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

这篇关于p:fileUpload required ="true";和自定义验证器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆