JSF 2.0: Проверьте равенство 2 Полей InputSecret (подтвердите пароль) без написания кода?

Я разрабатываю чистое приложение JavaEE6 с JSF 2.0 и Glassfish. Моей реализацией JSF является Primefaces (около Mojarra, обеспеченного Glassfish).

Я хочу проверить, равны ли значения 2 полей пароля в форме JSF. Со Швом существует аккуратный компонент <s:validateEquality for="pw1"/>. Я хочу, делают к тому же безо Шва, просто с помощью JSF (или возможно компонент библиотеки JSF). До сих пор я только видел примеры, которые проверяют форму с нестандартным элементом верификации. Но я хотел бы сравнить поля, не пишущий код Java или код JavaScript. Это возможно?

Это, на что это похоже со Швом:

...
<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>
...
6
задан Ingo Fischer 28 May 2014 в 08:41
поделиться

2 ответа

Вот как я, наконец, сделал это, что мне нравится, потому что это коротко и легко. Единственная проблема заключается в том, что его нельзя использовать повторно, но поскольку мне это нужно только в одном случае, я лучше сохраню несколько LOC и сделаю это таким образом. Фрагмент моего обзора:

<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 Backing Bean (только важная часть):

@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);
    }
  }
3
ответ дан 8 December 2019 в 05:53
поделиться

Модуль Seam3 Faces будет поддерживать "валидацию форм с перекрестными полями" в ближайшем релизе Alpha3. Это лучший вариант для решения с минимальным кодом, смотрите этот блог, чтобы узнать, как это сделать.

В качестве альтернативы я сделал это программно, используя тег f:attribute для передачи clientId другого поля формы в пользовательский валидатор, затем используя UIComponent, переданный в пользовательский валидатор, для доступа к другим полям по id.

Вот файл facelet:

<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>

Вот класс валидатора:

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."));
    }
}
}
6
ответ дан 8 December 2019 в 05:53
поделиться
Другие вопросы по тегам:

Похожие вопросы: