【问题标题】:JSF validation pattern for input control输入控件的 JSF 验证模式
【发布时间】:2014-02-17 05:04:14
【问题描述】:

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

【问题讨论】:

  • 所有关键字用“-”隔开,像这样输入:h-e-l-l-o ?
  • @Omar : 没有。意思是每个标签(关键字)用“-”分隔,比如:hello - bye - ...

标签: regex validation jsf webpage


【解决方案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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-04-04
    • 1970-01-01
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多