PrimeFaces提供验证标签以在服务器端验证我们的数据。 <p:ajax>用于执行Ajax验证。在这里, 我们正在创建一个示例, 该示例接受两个输入并在服务器端进行验证。
本示例包括以下文件。
JSF文件
// ajax-validation.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>ajax-validation</title>
</h:head>
<h:body>
<h:form>
<p:panel id="panel-id" header="Add a User">
<p:messages id="msgs" />
<h:panelGrid columns="3" cellpadding="5">
<p:outputLabel for="firstname" value="Firstname:" />
<p:inputText id="firstname" value="#{ajaxValidation.firstname}" required="true" label="Firstname">
<f:validateLength minimum="2" />
</p:inputText>
<p:message for="firstname" display="icon" />
<p:outputLabel for="lastname" value="Lastname:" />
<p:inputText id="lastname" value="#{ajaxValidation.lastname}" label="Lastname" required="true">
<f:validateLength minimum="2" />
<p:ajax update="msgLastname" event="keyup" />
</p:inputText>
<p:message for="lastname" id="msgLastname" display="icon" />
</h:panelGrid>
<p:commandButton value="Save" update="panel-id" actionListener="#{ajaxValidation.save}" icon="ui-icon-check" />
</p:panel>
</h:form>
</h:body>
</html>
ManagedBean
// AjaxValidation.java
package com.srcmini;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
@ManagedBean
public class AjaxValidation {
private String firstname;
private String lastname;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void save() {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Welcome " + firstname + "" + lastname));
}
}
执行后将产生以下输出。
输出
它在客户端验证数据并产生以下数据。
评论前必须登录!
注册