2015-06-19 141 views
0

我正在嘗試實現表單的驗證,但在我填寫數字或字符時不接受。JSF中的驗證

這是我login.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:ui="http://xmlns.jcp.org/jsf/facelets" 
     xmlns:c="http://xmlns.jcp.org/jsp/jstl/core" 
     xmlns:h="http://xmlns.jcp.org/jsf/html" 
     xmlns:f="http://xmlns.jcp.org/jsf/core"> 

    <h:body> 
     <ui:composition template="./templates/template.xhtml"> 
      <ui:define name="content"> 
       <p><h:link outcome="/index" value="To Home Page" /></p> 
       <h:form> 
        Username: <h:inputText id="username" value="#{user.name}" required="true" requiredMessage="username name is required"><f:validator validatorId="usernameValidator" /></h:inputText><br/> 
        Password: <h:inputText id="password" value="#{user.password}" required="true" requiredMessage="password is required"><f:validator validatorId="passwordValidator" /></h:inputText><br/> 
        Email: <h:inputText id="Email" value="#{user.email}" required="true" requiredMessage="email is required"><f:validator validatorId="emailValidator" /></h:inputText> 

        <h:commandButton id="cBtn2" value="Submit" action="home"/> 
       </h:form> 

      </ui:define> 
     </ui:composition> 

    </h:body> 
</html> 

而我的驗證類:

package Validation; 


import javax.faces.application.FacesMessage; 
import javax.faces.component.UIComponent; 
import javax.faces.context.FacesContext; 
import javax.faces.validator.Validator; 
import javax.faces.validator.ValidatorException; 

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

     String password = (String) value; 

     if(!password.contains("([1-9]/[A-Z]-[1-9]-[1-9]-[1-9](-[1-9])?")) { 
      FacesMessage message = new FacesMessage(); 
      message.setSeverity(FacesMessage.SEVERITY_ERROR); 
      message.setSummary("Value you entered is not valid - Please enter a value which contains only [1-9]/[A-Z]."); 
      message.setDetail("Value you entered is not valid - Please enter a value which contains only [1-9]/[A-Z]."); 
      context.addMessage("userForm:Password", message); 
      throw new ValidatorException(message); 
     } 
    } 
} 

任何人都知道它爲什麼不接受這個,當我填寫管理員?

+1

所以基本上,你的問題歸結爲*爲什麼我的正則表達式沒有按預期工作*? –

+0

@LuiggiMendoza是正確的你的正則表達式是這裏的問題 – smoggers

+0

是的確,如何爲此創建正確的正則表達式? –

回答

0

String.contains不需要正則表達式;改爲嘗試String.matches

對於只匹配數字和字符的正則表達式,請嘗試^\w+$。這基本上說,「匹配字符串的開頭,然後至少匹配一個'單詞'字符(它是一個數字或一個字母),然後匹配字符串的末尾」。

+0

而正確的正則表達式用於檢查填充的值是否只能是數字或字符? –

+0

編輯我的答案包括那 –