2010-05-25 12 views
5

Ben JSF 2.0 ve GlassFish ile saf JavaEE6 uygulama geliştiriyorum. JSF uygulamam, Primefaces (Glassfish tarafından sağlanan Mojarra'nın yanında).JSF 2.0: Kod yazmadan 2 InputSecret Alanının eşitliğini (şifreyi onaylayın) doğrulayın.

Bir JSF formundaki 2 parola alanı değerlerinin eşit olup olmadığını doğrulamak istiyorum. Seam ile , düzgün bileşen <s:validateEquality for="pw1"/> yoktur. Sadece (veya bir JSF kütüphanesi belki bir bileşeni) JSF kullanarak, Dikiş olmadan aynı yapmak istiyorum. Şimdiye kadar sadece formu özel bir doğrulayıcı ile doğrulayan örnekleri gördüm. Ama Java kodu veya Javascript kodu yazmadan alanları karşılaştırmak istiyorum. Bu mümkün mü?

o Dikiş ile neye benzediğini Bu:

... 
<h:inputSecret id="passwort" value="#{personHome.instance.password}" 
    redisplay="true" required="true"> 
    <f:validateLength minimum="8"/> 
    <a:support event="onblur" reRender="passwortField" bypassUpdates="true" ajaxSingle="true" /> 
</h:inputSecret> 
...  
<h:inputSecret id="passwort2" required="true" redisplay="true"> 
    <!-- find the JSF2.0-equivalent to this tag: --> 
    <s:validateEquality for="passwort"/> 
    <a:support event="onblur" reRender="passwort2Field" bypassUpdates="true" ajaxSingle="true" /> 
</h:inputSecret> 
... 
+0

öyleyse ... eğer 'kodsuz' bir çözüm yoksa, 'kod' ile en temiz çözüm nedir? – ifischer

cevap

3

Bu kısa ve kolay neden i gibi i sonunda yaptılar yoludur

İşte facelet dosya. Tek sorun, gerçekten yeniden kullanılabilir değil, ama sadece bir durumda buna ihtiyacım olduğu için, bazı LOC'leri kaydetmeyi ve bu şekilde yapmayı tercih ediyorum. Benim görünümden Parçacığı:

<h:inputSecret id="password" value="#{personHome.person.password}"> 
    <f:ajax event="blur" render="passwordError" /> 
</h:inputSecret> 
<h:message for="password" errorClass="invalid" id="passwordError" /> 

<h:inputSecret id="password2" validator="#{personHome.validateSamePassword}"> 
    <f:ajax event="blur" render="password2Error" /> 
</h:inputSecret> 
<h:message for="password2" errorClass="invalid" id="password2Error" /> 

My Taşıyıcı Bean (sadece önemli bir parçası):

@Named @ConversationScoped 
public class PersonHome { 
    private Person person; 

    public Person getPerson() { 
    if (person == null) return new Person(); 
    else return person; 
    } 

    public void validateSamePassword(context:FacesContext, toValidate:UIComponent, value:Object) { 
    String confirmPassword = (String)value; 
    if (!confirmPassword.equals(person.getPassword()) { 
     FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Passwords do not match!", "Passwords do not match!") 
     throw new Validatorexception(message); 
    } 
    } 
6

o yakın Alpha3 kurtulur içinde Seam3 Faces module "Çapraz alan form doğrulama" destekleyecektir. Bu, minimum bir kod çözümü için en iyi bahistir, bir howto için bu blog'a bakın.

Alternatif olarak, başka bir form alanının clientId'sini özel bir validator'a geçirmek için f: attribute etiketini kullanarak programatik olarak yaptım, sonra da kimliği doğrulanan diğer erişime erişmek için UIComponent'i özel doğrulama aracına geçirdi.

<h:outputLabel value="Enter your email address" rendered="#{!cc.attrs.registration.subRegistration}" /> 
<h:inputText label="Email" id="textEmail1" value="#{cc.attrs.registration.email}" rendered="#{!cc.attrs.registration.subRegistration}" required="true" maxlength="128" size="35"></h:inputText> 
<h:message for="textEmail1" rendered="#{!cc.attrs.registration.subRegistration}"></h:message> 

<h:outputLabel value="Re-enter your email address confirmation:" rendered="#{!cc.attrs.registration.subRegistration and cc.attrs.duplicateEmailRequired}" /> 
<h:inputText label="Email repeat" id="textEmail2" rendered="#{!cc.attrs.registration.subRegistration and cc.attrs.duplicateEmailRequired}" maxlength="64" size="35"> 
    <f:validator validatorId="duplicateFieldValidator" /> 
    <f:attribute name="field1Id" value="#{component.parent.parent.clientId}:textEmail1" /> 
</h:inputText> 
<h:message for="textEmail2" rendered="#{!cc.attrs.registration.subRegistration and cc.attrs.duplicateEmailRequired}"></h:message> 

İşte doğrulayıcı sınıfı var:

package ca.triumf.mis.trevents.jsf.validator; 

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

@FacesValidator(value="duplicateFieldValidator") 
public class DuplicateFieldValidator implements Validator { 

@Override 
public void validate(FacesContext context, UIComponent component, Object value) 
     throws ValidatorException { 
    // Obtain the client ID of the first field from f:attribute. 
    System.out.println(component.getFamily()); 
    String field1Id = (String) component.getAttributes().get("field1Id"); 

    // Find the actual JSF component for the client ID. 
    UIInput textInput = (UIInput) context.getViewRoot().findComponent(field1Id); 
    if (textInput == null) 
     throw new IllegalArgumentException(String.format("Unable to find component with id %s",field1Id)); 
    // Get its value, the entered text of the first field. 
    String field1 = (String) textInput.getValue(); 

    // Cast the value of the entered text of the second field back to String. 
    String confirm = (String) value; 

    // Check if the first text is actually entered and compare it with second text. 
    if (field1 != null && field1.length() != 0 && !field1.equals(confirm)) { 
     throw new ValidatorException(new FacesMessage("E-mail addresses are not equal.")); 
    } 
} 
} 
3

Ben başarılı olmak için hem cevapların bir karışımını kullanmak zorunda kaldı.

Ifischers'ı kısa bir çözüm kullandım, ancak fasulye parolası alanım boş.

Yani bağlamdan UIInput almak Brian Leathem gelen satırları kullandı:

public void passwordValidator(FacesContext context, UIComponent toValidate, Object value) { 

    UIInput passwordField = (UIInput) context.getViewRoot().findComponent("registerForm:password"); 
    if (passwordField == null) 
     throw new IllegalArgumentException(String.format("Unable to find component.")); 
    String password = (String) passwordField.getValue(); 
    String confirmPassword = (String) value; 
    if (!confirmPassword.equals(password)) { 
     FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Passwords do not match!", "Passwords do not match!"); 
     throw new ValidatorException(message); 
    } 
} 
0

Apache MyFaces ExtVal ile kolayca yapabilirsiniz.

-1

Düzenlendi: okumadan önce, bu çözüm mükemmel çalıştığını düşünün lütfen, ve bunu gibi değildi sırf cevabı Temmuz 2012 tarihinden itibaren, bu nedenle aşağı beni oy kullanmayın lütfen. Dünya değişti ve şimdi daha iyi bileşenler ve çözümlerimiz var. solüsyon olmadan

, ben çirkin bir şekilde doğrulama yapmak zorunda kaldı (önerilmez). En azından daha iyi bir çözüm bulana kadar çalışır. eylem döndüren yöntemde

, ben her iki değeri kontrol farklı değerler söz konusu olduğunda, ben bağlama hata iletileri ekleyebilir ve navigasyon işleyicisi için boş döner.

package com.jsf.beans.user; 

import javax.faces.bean.ManagedBean; 
import javax.faces.bean.RequestScoped; 
import javax.faces.component.html.HtmlInputSecret; 

import org.apache.commons.lang.StringUtils; 

import com.pichler.jsf.beans.base.JsfViewBean; 

@ManagedBean(name = "changePassword") 
@RequestScoped 
public class ChangePassword extends JsfViewBean { 
private HtmlInputSecret inputSecret1, inputSecret2; 

/** 
* @return the inputSecret1 
*/ 
public HtmlInputSecret getInputSecret1() { 
    return inputSecret1; 
} 

/** 
* @param inputSecret1 
*   the inputSecret1 to set 
*/ 
public void setInputSecret1(HtmlInputSecret inputSecret1) { 
    this.inputSecret1 = inputSecret1; 
} 

/** 
* @return the inputSecret2 
*/ 
public HtmlInputSecret getInputSecret2() { 
    return inputSecret2; 
} 

/** 
* @param inputSecret2 
*   the inputSecret2 to set 
*/ 
public void setInputSecret2(HtmlInputSecret inputSecret2) { 
    this.inputSecret2 = inputSecret2; 
} 

private String password1, password2; 

public String alterar() { 
    if (!StringUtils.equals(password1, password2)) { 
     addErrorMessage(inputSecret1.getClientId(), 
       "As senhas não coincidem"); 
     addErrorMessage(inputSecret2.getClientId(), 
       "As senhas não coincidem"); 
     return null; 
    } 
    return null; 
} 

/** 
* @return the password1 
*/ 
public String getPassword1() { 
    return password1; 
} 

/** 
* @param password1 
*   the password1 to set 
*/ 
public void setPassword1(String password1) { 
    this.password1 = password1; 
} 

/** 
* @return the password2 
*/ 
public String getPassword2() { 
    return password2; 
} 

/** 
* @param password2 
*   the password2 to set 
*/ 
public void setPassword2(String password2) { 
    this.password2 = password2; 
} 

}

* JsfViewBean "addMessages" gibi bazı ortak yöntemleri vardır sadece sınıftır.

4

Bu çok basit bir şekilde Primefaces etiketini kullanabilirsiniz: Eğer MTU yarar kütüphanesini OmniFaces kullanıyorsanız, o zaman <o:validateEqual> kullanabilirsiniz

<p:password id="password" value="#{bean.password}" match="repeated_password" /> 

<p:password id="repeated_password" value="#{bean.password}" /> 
2

. Ayrıca özel bir mesajın ayarlanmasına da izin verir. showcase, parola onayını doğrulama genel kullanım tablosunu gösteren canlı bir örneğe sahiptir. Doğrulayıcıyı çağırmadan önce modeli güncellemek için ajax'a bile ihtiyacınız yoktur (your own approach gibi). gerekli

<h:inputSecret id="password" value="#{personHome.person.password}" /> 
<h:message for="password" /> 

<h:inputSecret id="password2" /> 
<h:message for="password2" /> 

<o:validateEqual components="password password2" 
    message="Passwords do not match!" showMessageFor="password2" /> 

Hayır Java kodu:

İşte asgari gerekli şifre.

İlgili konular