tags:

views:

95

answers:

1

Is there a proper way to access other form fields from inside a validator? Is there another solution than:

context.getViewRoot().findComponent("formid:exampleField:example")?

f.e I want to validate a city field inside a custom validator and checking if country is US.

+1  A: 

Re-read your question and I am going to interpret it as this:

"You would like to write a custom validator that checks that if a city field exists, the country field is equal to 'US'"

So, I would look at going about this in the following fashion:

First create a validator interface:

@Documented
@ValidatorClass(value=CountryEqualsUSValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CountryEqualsUS {

    String message() default "The country should be US for the city provided";

}

Then create a validator class:

public class CountryEqualsUSValidator implements Validator<CountryEqualsUS> {

    public void initialize(CountryEqualsUS arg0) {
    }

    public boolean isValid(Object value) {

        if(value != null && value instanceof YourBeanClass) {

            YourBeanClass yourBeanClass = (YourBeanClass) value;

            if(/*some test logic here*/) {
                return true;
            else {
                return false;
            }

        }

        return false;

    }

}

Then on the class that you want to validate:

@CountryEqualsUS
public class YourBeanClass {

    ...

}

Then, finally, on your controller/action class, when the form is submitted, the city is a value for which you want to check the country, add this method and call it:

public boolean doValidation(YourBeanClass yourBeanClass) {

    ClassValidator requestValidator = new ClassValidator(yourBeanClass.getClass());
    InvalidValue[] validationMessages = requestValidator.getInvalidValues(yourBeanClass);

    if (validationMessages != null && validationMessages.length > 0) {

        for (int i = 0; i < validationMessages.length; i++) {

            //Add a validation message to be displayed to the user

        }

        return false;

    }
        return true;
}
Aaron Chambers