【问题标题】:PrimeFaces How to validate uploaded file name?PrimeFaces 如何验证上传的文件名?
【发布时间】:2017-05-17 09:56:17
【问题描述】:

有没有人知道如何在 PrimeFaces 中使用验证消息来实现对 uploadFile 的验证?

查看:

<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,如果不是 - 向用户显示“文件名错误”消息。我的代码不起作用。无论文件名如何,都不会显示消息。

谢谢。

【问题讨论】:

  • 文件名够你用吗???
  • Yagami Light,对不起,我没有得到你的问题。你什么意思?
  • 你的问题不清楚,请问有没有办法说这个文件名是不是拉丁Unicode???
  • @ Yagami Light,在我的代码中,我有覆盖验证方法来检查 Unicode 是否为拉丁语。在调试模式下它工作得很好。生成验证消息。但问题是该验证消息从未向用户显示。
  • 尝试在ManagedBean 中添加其他消息类型,例如MyUtil.addErrorMessage("ERROR");,不要忘记在primefaces.org/showcase/ui/message/messages.xhtml 中使用&lt;p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /&gt; 示例

标签: java validation file-upload primefaces


【解决方案1】:

有很多方法可以让你的 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,则此解决方案的大+ 信息甚至不会进入实体级别,并且您不必设置条件来验证@ 987654328@ 在 managedBean 中是 NotEmptyNotBlank

来自您的 ManagedBean

page.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 的好方法。

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2017-12-30
    • 2014-11-06
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多