有谁知道如何在 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:inputText
为 NotEmpty
和 NotBlank
,则信息甚至不会进入实体级别,并且您不必在托管Bean 中设置条件来验证 p:inputText
是否为 NotEmpty
和 NotBlank
来自您的 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/