Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom validator in smartGWT?

Tags:

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

like image 645
javaNoober Avatar asked Mar 23 '12 10:03

javaNoober


2 Answers

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.

like image 99
gpapaz Avatar answered Nov 08 '22 11:11

gpapaz


Can't you do something like:

CustomValidator cv = new CustomValidator() {

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

Then set you TimeItem validator:

timeItem.setValidators(cv);

Of course you can't use '<' to compare the values of your TimeItems. But convert to time objects and compare them.

like image 27
Eric C. Avatar answered Nov 08 '22 09:11

Eric C.