java - PrimeFaces 如何验证上传的文件名?

标签 java validation file-upload primefaces

有谁知道如何在 PrimeFaces 中使用验证消息来实现上传文件的验证吗?

查看:

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

我需要检查上传的文件名是否采用拉丁 Unicode,如果不是,则向用户显示消息“文件名错误”。我的代码不起作用。无论文件名如何,都不会显示任何消息。

谢谢。

最佳答案

有很多方法可以让消息从你的 ManagedBean 中显示

来自您的实体

实体.java

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

并在您的 page.xhtml 中

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

此解决方案的最大优点是,如果 p:inputTextNotEmptyNotBlank,则信息甚至不会进入实体级别,并且您不必在托管Bean 中设置条件来验证 p:inputText 是否为 NotEmptyNotBlank

来自您的 ManagedBean

页面.xhtml

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

在你的 ManagedBean.java 中

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

您可以在Primefaces messages example web site中找到最好的例子咆哮消息也是显示消息的好方法 Primefaces growl example web site .

希望对您有帮助。

关于java - PrimeFaces 如何验证上传的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41441288/

相关文章:

java - 在非Activity类android中读取资源文件

java.rmi.NotBoundException

java - 整个窗口的按钮 - Java

javascript - Angular.js - 表单验证会发出任何事件吗?

ruby - 使用纯 Ruby 脚本将进度上传到 S3

java - JMX本地监控的访问控制

validation - Vuex 是放置验证规则的地方吗?

ASP.NET:仅在单击“提交”时执行验证

java - 将文件从 JSP 发送到调用接口(interface)方法的 Controller - 如何从该请求上传文件?

php - Codeigniter上传库获取Thumb文件名