highlighting fields with s:validateForm
teacurran Sep 8, 2011 11:34 PMIs it possible to use s:validateForm and have it highlight the problematic fields?
It was highlighting only a single field for us, and when I updated to 3.0.2 it now highlights all fields in the view if there is an error. I want to programmatically control which fields get highlighted.
It also only displays the first error I put into the arrayList. I feel like it should display all errors generated. This is less of a problem for me though.
This is my class:
@FacesValidator( "patientSearchValidator" )
public class PatientSearchValidator
implements Validator {
@Inject
private InputElement< String > fieldFirstName;
@Inject
private InputElement< String > fieldLastName;
@Inject
private InputElement< String > fieldEmail;
@Inject
private InputElement< String > fieldState;
@Inject
private InputElement< String > fieldZipCode;
@Inject
Messages messages;
@Override
public void validate(
final FacesContext facesContext,
final UIComponent uiComponent,
final Object values )
throws ValidatorException {
final ArrayList< FacesMessage > errors = new ArrayList< FacesMessage >();
fieldFirstName.getComponent().setValid( true );
fieldLastName.getComponent().setValid( true );
fieldState.getComponent().setValid( true );
fieldZipCode.getComponent().setValid( true );
if ( StringUtils.isEmpty( this.fieldState.getValue() )
&& StringUtils.isEmpty( this.fieldZipCode.getValue() ) ) {
fieldState.getComponent().setValid( false );
fieldZipCode.getComponent().setValid( false );
errors.add( this.createError( "Either State or Zip code is required" ) );
}
if ( StringUtils.isEmpty( this.fieldFirstName.getValue() )
&& StringUtils.isEmpty( this.fieldLastName.getValue() ) ) {
fieldFirstName.getComponent().setValid( false );
fieldLastName.getComponent().setValid( false );
errors.add( this.createError( "Either First Name or Last Name is required" ) );
}
if ( !StringUtils.isEmpty( this.fieldZipCode.getValue() ) ) {
if ( !this.fieldZipCode.getValue().matches( Constants.REGEX_ZIP_CODE ) ) {
fieldZipCode.getComponent().setValid( false );
errors.add( this.createError( "Zip Code entered is invalid" ) );
}
}
if ( errors.size() > 0 ) {
throw new ValidatorException( errors );
}
}
public FacesMessage createError(
final String value ) {
final FacesMessage message = new FacesMessage();
message.setDetail( value );
message.setSummary( value );
message.setSeverity( FacesMessage.SEVERITY_ERROR );
return message;
}
}