2013-11-21 4 views
0

сегодня я попробовал richfaces. Я хотел создать форму для регистрации пользователя , и я хотел использовать пользовательские валидаторы. Вот JSF часть:JSF Richfaces и пользовательская проверка

<ui:composition template="/templates/master.xhtml" > 

     <ui:define name="content"> 

      <center> 
       <h:outputText value="New User Registration" /> 
      </center> 

      <h:form> 

       <rich:panel> 

        <h:panelGrid columns="3" > 

         <h:outputText value="Username:" /> 
         <h:inputText id="username" value="#{registerService.userName}"> 
          <!-- <f:validator validatorId="userNameValidator"/> --> 
          <rich:validator /> 
         </h:inputText> 
         <h:message id="m_username" for="username" style="color:red" /> 

         <h:outputText value="Password:" /> 
         <h:inputSecret id="password" value="#{registerService.password}"> 
          <f:validator validatorId="passwordValidator" /> 
         </h:inputSecret> 
         <h:message id="m_password" for="password" style="color:red" /> 

         <h:outputText value="Confirm Password:" /> 
         <h:inputSecret id="confirmPassword" value="#{registerService.confirmPassword}"> 
          <f:validator validatorId="passwordConfirmValidator" /> 
          <f:attribute name="passwordId" value="#{component.parent.parent.clientId}:password" /> 
         </h:inputSecret> 
         <h:message id="m_confirmPassword" for="confirmPassword" style="color:red" />  

         <h:outputText value="Lastname:" /> 
         <h:inputText id="lastname" value="#{registerService.lastName}"> 
          <f:validator validatorId="nameValidator" /> 
         </h:inputText> 
         <h:message id="m_lastname" for="lastname" style="color:red" /> 

         <h:outputText value="Firstname:" /> 
         <h:inputText id="firstname" value="#{registerService.firstName}"> 
          <f:validator validatorId="nameValidator" /> 
         </h:inputText> 
         <h:message id="m_firstname" for="firstname" style="color:red" /> 

         <h:outputText value="Date of Birth: " /> 
         <rich:calendar value="#{registerService.birthDate}" /> 
         <h:outputText value=""/> 

         <h:outputText value="E-Mail:" /> 
         <h:inputText id="email" value="#{registerService.eMail}" > 
          <f:validator validatorId="emailValidator" /> 
         </h:inputText> 
         <h:message id="m_email" for="email" style="color:red" />  

         <h:outputText value="Confirm E-Mail:" /> 
         <h:inputText id="confirmEmail" value="#{registerService.confirmEMail}"> 
          <f:validator validatorId="emailConfirmValidator" /> 
          <f:attribute name="emailId" value="#{component.parent.parent.clientId}:email" /> 
         </h:inputText> 
         <h:message id="m_confirmEmail" for="confirmEmail" style="color:red" /> 

        </h:panelGrid> 

        <h:commandButton type="submit" value="Submit" action="#{registerService.addUser}" > 
         <f:ajax execute="@form" render="m_username m_password m_confirmPassword m_lastname m_firstname m_email m_confirmEmail" /> 
        </h:commandButton>    
        <h:commandButton type="reset" value="Reset" />   

       </rich:panel> 

      </h:form> 

     </ui:define> 

    </ui:composition> 

, например, валидатор:

@FacesValidator(value="emailValidator") 
public class EmailValidator implements Validator { 

    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { 
     String email = (String) value; 
     FacesMessage message = null; 

     if(email == null || email.isEmpty()) { 
      message = new FacesMessage ("Please enter a E-Mail!", "Email Validation Error"); 
      message.setDetail("You havent entered a valid E-Mail yet!"); 
      message.setSeverity(FacesMessage.SEVERITY_ERROR); 

      throw new ValidatorException(message); 
     } 

     if(!email.contains("@")) { 
      message = new FacesMessage ("Invalid E-Mail!", "Email Validation Error"); 
      message.setDetail("E-Mail does not contain '@'"); 
      message.setSeverity(FacesMessage.SEVERITY_ERROR); 

      throw new ValidatorException(message); 
     } 

     Matcher matcher = Regex.EMAIL_PATTERN_COMPILED.matcher(email); 

     if(!matcher.matches()) { 
      message = new FacesMessage ("Invalid E-Mail!", "Email Validation Error"); 
      message.setDetail("E-Mail contains forbidden characters or does not match the E-Mail pattern!"); 
      message.setSeverity(FacesMessage.SEVERITY_ERROR); 

      throw new ValidatorException(message); 
     } 

     if(email.length() > 64) { 
      message = new FacesMessage ("Invalid E-Mail!", "Email Validation Error"); 
      message.setDetail("E-Mail is to long (max. 64 characters)!"); 
      message.setSeverity(FacesMessage.SEVERITY_ERROR); 

      throw new ValidatorException(message); 
     } 
    } 
} 

, кажется, что эти пользовательские валидаторы Арента работать внутри тег. Что мне нужно сделать, чтобы заставить их работать. или я должен использовать что-то другое для реализации проверки.

ответ

1

нам форма-тег внутри богатых: панели тега, и он будет работать

<rich:panel> 

    <h:form> 

     .... 

    </h:form> 

<rich:panel> 

Вы также можете использовать аннотации для проверки с помощью RichFaces, как вы уже пробовали:

<h:outputText value="Username:" /> 
<h:inputText id="username" value="#{registerService.userName}"> 
    <!-- <f:validator validatorId="userNameValidator"/> --> 
    <rich:validator /> 
</h:inputText> 
<h:message id="m_username" for="username" style="color:red" /> 

В вашем бобе вы можете использовать это, например:

@ManagedBean 
@RequestScoped 
public class ValidationBean { 
    @Size(min = 3, max = 12) 
    private String name = null; 
    @Pattern(regexp = "^[\\w\\-]([\\.\\w])+[\\w][email protected]([\\w\\-]+\\.)+[a-zA-Z]{2,4}$", message = "Bad email") 
    private String email = null; 
    @Min(value = 18) 
    @Max(value = 99) 
    private Integer age; 
    private String country; 
    private String jobTitle; 
    @AssertTrue 
    private boolean agreed = true; 

    public boolean isAgreed() { 
     return agreed; 
    } 

    public void setAgreed(boolean agreed) { 
     this.agreed = agreed; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getEmail() { 
     return email; 
    } 

    public void setEmail(String email) { 
     this.email = email; 
    } 

    public Integer getAge() { 
     return age; 
    } 

    public void setAge(Integer age) { 
     this.age = age; 
    } 

    public String getCountry() { 
     return country; 
    } 

    public void setCountry(String country) { 
     this.country = country; 
    } 

    public String getJobTitle() { 
     return jobTitle; 
    } 

    public void setJobTitle(String jobTitle) { 
     this.jobTitle = jobTitle; 
    } 
} 

Source

<rich:validator /> 

Будет автоматически проверять ввод пользователя из-за этих аннотаций. Я думаю, что это облегчает работу, и у вас меньше работы.

Смежные вопросы