Search code examples
javasmartgwt

Create a validator in SmartGwt to check if String is an Integer


I have a TextItem and I want to set a Validator on it so it checks that the input is a integer ONLY.

TextItem textItem = new TextItem();
textItem.setValidator(myValidator)

How should I create my myValidator to check this? I have:

myValidatorcv = new CustomValidator() {

        @Override
        protected boolean condition(Object value) {
            if (Integer.parseInt(value);){
                return true;
            }else
                return false;
            }
        }
};

Is that the best way to do this? Also do I also need to catch the number format exception inside the validator?


Solution

  • Is that the best way to do this?

    Probably. Any time you can leverage the built-in capability of the framework, that's usually an indicator of a good solution. There are some that might say that exception driven programming isn't the best approach because of the cost to handle them, but that's up to you.

    Also do I also need to catch the number format exception inside the validator?

    Yes, that's how you will know if it fails or not.

    myValidatorcv = new CustomValidator() {
    
            @Override
            protected boolean condition(Object value) {
                try {
                    Integer.parseInt(value.toString());
                    return true;
                } catch (NumberFormatException) {
                    return false;
                }
            }
    };
    

    I'm not totally familiar with this framework, but if you can utilize generics to ensure that the object you are validating is an Integer or String rather than an Object, that would be better.