问题
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