Search code examples
smartgwt

How to create a custom validator in smartGWT?


I got 2 TimeItems, I want to be able to validate that the value of the second item is not bigger than the first.

I'm aware that I must inherit from CustomValidator and place my validation logic in #condition, I can retrieve the value of the validated item with #getFormItem, but I got no idea on how to pass the value of the first field onto the validator


Solution

  • Or for better readability and code maintainability, use a nested class:

    class YourClass {
        private TimeItem timeItem1;
        private TimeItem timeItem2;
    
        public YourClass() {
           //Instantiate your TimeItem objects.
           ...
    
           //Set the validator
           MyCustomValidator validator = new MyCustomValidator();
           timeItem1.setValidators(validator);
    
           /Assuming that both items should check validation.
           timeItem2.setValidators(validator);
        }
    
        ...
        class MyCustomValidator extends CustomValidator  {
    
             @Override
             protected boolean condition(Object value) {
                //Validate the value of timeItem1 vs the timeItem2
                //Overide equals or transform values to 
                if (timeItem1.getValueAsString().equals(timeItem2.getValueAsString()) {
    
                //Return true or false.
                }
              return false;
             }
        ...
        }
    }
    

    And if you prefer create getter methods for the two TimeItem objects to avoid using private attributes in your nested class.