2011-03-31 15 views
5

आप जेएसएफ वैलिडेटर में समानता के लिए दो स्ट्रिंग की तुलना कैसे करेंगे?जेएसएफ वैलिडेटर समानता के लिए स्ट्रिंग्स की तुलना

if (!settingsBean.getNewPassword().equals(settingsBean.getConfirmPassword())) { 
    save = false; 
    FacesUtils.addErrorMessage(null, "Password and Confirm Password are not same", null); 
} 

उत्तर

17

एक सामान्य Validator का प्रयोग करें और दूसरे घटक की विशेषता के रूप में पहले घटक का मूल्य गुजरती हैं।

<h:inputSecret id="password" binding="#{passwordComponent}" value="#{bean.password}" required="true" 
    requiredMessage="Please enter password" validatorMessage="Please enter at least 8 characters"> 
    <f:validateLength minimum="8" /> 
</h:inputSecret> 
<h:message for="password" /> 

<h:inputSecret id="confirmPassword" required="#{not empty passwordComponent.value}" 
    requiredMessage="Please confirm password" validatorMessage="Passwords are not equal"> 
    <f:validator validatorId="equalsValidator" /> 
    <f:attribute name="otherValue" value="#{passwordComponent.value}" /> 
</h:inputSecret> 
<h:message for="confirmPassword" /> 

(note that binding in above example is as-is; you shouldn't bind it to a bean property!)

@FacesValidator(value="equalsValidator") 
public class EqualsValidator implements Validator { 

    @Override 
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { 
     Object otherValue = component.getAttributes().get("otherValue"); 

     if (value == null || otherValue == null) { 
      return; // Let required="true" handle. 
     } 

     if (!value.equals(otherValue)) { 
      throw new ValidatorException(new FacesMessage("Values are not equal.")); 
     } 
    } 

} 

साथ

आप JSF उपयोगिता पुस्तकालय OmniFaces उपयोग करने के लिए होता है, तो आप इस के लिए <o:validateEquals> उपयोग कर सकते हैं। "पासवर्ड की पुष्टि करें" का सटीक मामला <o:validateEqual> showcase पर प्रदर्शित किया गया है।

+0

हाय बलुस, क्या इनपुट सेक्रेट घटक को बाध्य किए बिना ऐसा करने का कोई और तरीका है? – c12

+0

आप आईडी को हार्डकोड कर सकते हैं और इसके बजाय इसे पास कर सकते हैं। जैसे '' और फिर घटक प्राप्त करने के लिए 'UIViewRoot # findComponent()' का उपयोग करें। हालांकि यह केवल बेकार है। बाध्यकारी के खिलाफ उलझन क्यों? यह मुझे समझ में नहीं आता है। – BalusC

+0

घटकों के लिए बाइंडिंग जोड़ते समय अतिरिक्त ओवरहेड (मेमोरी वार) नहीं है? यह शायद न्यूनतम है, लेकिन सिर्फ एक सवाल है। – c12

संबंधित मुद्दे