How to create a custom validator in smartGWT?

I have 2 TimeItems, I want to check that the value of the second element is not greater than the first.

I know that I have to inherit from CustomValidator and put the validation logic in #condition, I can get the value of the checked element using #getFormItem, but I did not know how to pass the value of the first field to the validator

+5
source share
3 answers

Or for better readability and code support, 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 to create getter methods for two TimeItem objects to avoid using private attributes in your nested class.

+7
source

You cannot do something like:

CustomValidator cv = new CustomValidator() {

        @Override
        protected boolean condition(Object value) {
            if (otherTimeItem.getValue()<value){
                return true;
            }else
                return false;
            }
        }
};

Then install the TimeItem validator for you:

timeItem.setValidators(cv);

, '<' TimeItems. .

+2

I know this is an old post, but I think there is a better solution (at least in later versions of SmartGWT). So, this applies to everyone who is interested in:

You can get the whole record to be checked with getRecord(). And then you can get any field value by simply requesting the attributes of the record:

CustomValidator validator = new CustomValidator() {
    @Override
    protected boolean condition(Object rawValue) {
        Record validatedRecord = getRecord();
        String field1 = validatedRecord.getAttribute(FIELD1_NAME);
        String field2 = validatedRecord.getAttribute(FIELD2_NAME);

        return field2 <= field1;
    }
}

This is better because you do not need to keep links to your fields.

0
source

All Articles