PrimeFaces How to validate uploaded file name?

2019-08-01 00:08发布

问题:

Does any body know how to implement validation with validation message to uploadFile in PrimeFaces?

View:

<p:fileUpload id="upload" 
fileUploadListener="#{fileBean.handleFileUpload}"
update="uploads" auto="true" multiple="true" skinSimple="true"> 
<f:validator validatorId="uploadValidator"/>
<p> <h:messages id="messages" /></p>
</p:fileUpload>

FileBean:

List<UploadedFile> uploadedFiles;

    public void handleFileUpload(FileUploadEvent event) {
        if (uploadedFiles == null) {
            uploadedFiles = new ArrayList<>();
        }
        uploadedFiles.add(event.getFile());
    }

uploadValidator.java

@FacesValidator("uploadValidator")
public class UploadValidator implements Validator {
    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        Part file = (Part) value;
        FacesMessage message=null;

        try {
            if (!file.getName().matches("\\w+"))
                message=new FacesMessage("Wrong file name");
            if (message!=null && !message.getDetail().isEmpty())
            {
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(message);
            }
        } catch (Exception ex) {
            throw new ValidatorException(new FacesMessage(ex.getMessage()));
        }
    }
}

I need to check if uploaded file name is on Latin Unicode and if not - show user a message "Wrong file name." My code doesn't work. No message is displayed no matter the file name.

Thank you.

回答1:

There is many way's to make a message appear from your managedBean

From your Entity

entity.java

@NotEmpty(message = "{validation.msg.notNull}")
@NotBlank(message = "{validation.msg.notBlank}")
@Column(name = "code", unique = true)
private String code;

and in your page.xhtml

<p:inputText id="code" ...  />
<p:message for="code" />

The big + with this solution that if the p:inputText is NotEmpty and NotBlank the informations doesn't even go to the entity level, and you don't have to make a condition to verify if the p:inputText is NotEmpty and NotBlank in your managedBean

From your ManagedBean

page.xhtml

<p:messages id="msgs" globalOnly="true" showDetail="true" closable="true"/>
<p:inputText id="code" ...  />
<p:commandButton  ... actionListener="#{managedBean.validate()}" update=":msgs"  />

and in your ManagedBean.java

public void validate(){
...
MyUtil.addErrorMessage("ERROR");
...
}

You can find the best example in the Primefaces messages example web site and the growl message is also a good way to show a message Primefaces growl example web site.

Hope that helped you.