Highlight field when Bean Validator fails

Just implementing a nice working Bean validator as described in

with the PassportNumberValidator.

It works fine, it validates and it displays the error when validation fails.

But how can I let the relevant field highlight in red as the standard validations do?

In my Entity:

@PublishEntityChangedEvents
@NamePattern("%s %s|firstName,lastName")
@Table(name = "USERLIFECYCLEMGMT_HR_USER")
@Entity(name = "userlifecyclemgmt_HrUser")
@Listeners("userlifecyclemgmt_HrUserEntityListener")
@ValidHrUserEndDate(groups = {Default.class, UiCrossFieldChecks.class})
public class HrUser extends StandardEntity {
    private static final long serialVersionUID = 4928671829969031784L;
    ....

Defining and assigning it like this, I can see that the Validator is not assigned to a specific field.

So how would I do that?

Hi, Edwin

CrossField validation is checking several attributes, by this reason we could not unambiguously which field should be highlighted in red.
But StandardEditor screen has validateAdditionalRules() method. You can override this method for your entity screen editor and add some logic and validation errors indicating the component (field).

Best regards,
Vera

Hi there,

I tried to do the validateAdditionalRules method, but although I would be able to validate what I need it still doesn’t highlight the field I associate the validation error with:

@Inject
private DateField<LocalDate> endDateField;    
...
@Override
protected void validateAdditionalRules(ValidationErrors errors) {
    super.validateAdditionalRules(errors);
    if(true){
        errors.add(endDateField,"That's wrong");
    }   
}

My solution in the end was as follows (Thank you Andrey B.)

@Install(to = "endDateField", subject = "validator")
private void endDateFieldValidator(LocalDate fieldValue) {
    boolean valid = false;
    if(getEditedEntity().getUsertype() == HrUserType.INTERNAL){
        valid = true;
    } else if (getEditedEntity().getEndDate() == null){
        valid = false;
    } else {
        Integer maxPeriodForExternalStaff = 549;
        LocalDate today = LocalDate.now();
        LocalDate maxDate = today.plusDays(maxPeriodForExternalStaff);
        valid = fieldValue.isBefore(maxDate);
    }
    if (!valid) {
        throw new ValidationException("The end date can be no later than 18 months after today's date.");
    }
}

You may have to look into the validateAdditionalRules as it doesn’t seem to highlight fields, at least not Date fields, I didn’t test other field types.

Thank you, we created an issue on github

1 Like