7

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Tiny
  • 27,221
  • 105
  • 339
  • 599
  • I didn't look in 4.0 source code yet, but the following answer for 3.4 may hold true for 4.0 as well: http://stackoverflow.com/questions/13865136/primefaces-3-4-fileupload-validator-not-fired/13868094#13868094 – BalusC Nov 12 '13 at 09:46
  • @BalusC : Is there any workaround to this? This can of course be checked in the respective JSF managed bean to see, if the `UploadedFile` object is `null` or not but doing so causes some JSF/PrimeFaces components like `` to be update unnecessarily which in turn, causes some costly queries to be fired upon the database which is plain wrong and clumsy. – Tiny Nov 27 '13 at 22:52
  • Theoretically, a custom renderer should do. Can't tell from top of head without checking the sources. – BalusC Nov 27 '13 at 23:54

1 Answers1

0

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"));
   }
 }
}
Noor Nawaz
  • 2,175
  • 27
  • 36
  • This can be done in a managed bean for sure but it is not a validator after all which is invoked and performs its job far before any associated properties/fields in a managed bean is populated. – Tiny May 11 '15 at 17:38