用于输入控件的JSF验证模式

时间:2014-01-26 11:00:26

标签: regex validation jsf webpage

我有一个JSF页面,我在这个页面中有一个inputtext。我从这个inputtext获取用户关键字。 我的问题是我想控制用户输入的关键字数量(用“ - ”分隔)并检查它们是否不超过特定数字。是否有任何验证模式或更好的方法来检查它们?

1 个答案:

答案 0 :(得分:1)

您可以使用Custom Validator通过定义实现Validator接口的java类来执行此验证,该接口应执行特定的所需验证。这是一个小例子,显示当用户键入关键字(以“ - ”分隔)超过预定的最大限制(例如5)时,传递到下一个字段时会弹出验证消息:

查看: index.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:f="http://java.sun.com/jsf/core"      
  xmlns:h="http://java.sun.com/jsf/html">

<h:head>
    <title>Custom Validator Example</title>
</h:head>
<h:body>

    <h:form>
        <h:panelGrid columns="3">
        Give strings separated by "-" : 
        <h:inputText id="input" size="30" required="true"  requiredMessage="Field required" value="#{myBean.myExpression}">
                <f:ajax event="blur" render="inputMessage" />
                <f:validator binding="#{myValidator}" />
        </h:inputText>
        <h:message for="input" id="inputMessage" style="color:red" />

        Enter your name:
        <h:inputText id="input1" required="true" requiredMessage="missed name" value="#{myBean.name}"  />
        </h:panelGrid>
    </h:form>
</h:body>

一个简单的托管bean: MyBean.java

 // imports
    @ManagedBean
    @RequestScoped
    public class MyBean implements Serializable {

        private String myExpression ;
        private String name ;

        // getters/setters

}

自定义验证程序: MyValidator.java

// imports
@ManagedBean
@ViewScoped
public class MyValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

        int max_limit = 5; // for example

        String expression = (String) value;
        String[] result = expression.split("-");
        int count=0;

        for(int i=0;i<result.length;i++){
            if (result[i].equals("")) continue;  // Empty keywords (e.g successive "-" caracters) are ignored. Else, just omit this line
            count++;
        }

        if (count > max_limit) {
            FacesMessage facesmsg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Exeeded allowed limit !",null);
            throw new ValidatorException(facesmsg);
        }
    }
}