P: fileUpload required = "true" and the custom validator does not work
Since the required <p:fileUpload> attribute still does not work in the PrimeFaces 4.0 finale, I tried to create a special 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 using <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 has never been called. Since I display images in <p:dataGrid> , this check is very necessary. Is there a way to check for an empty <p:fileUpload> ?
try it
@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")); } } }