Search code examples
gxt

Limit the number of decimal places a user can enter in a GXT grid cell


How can I limit the number of decimal places a user can enter in a GXT grid cell.

I can format the column config via column.setNumberFormat(...) but this just rounds the value to the defined format, e.g. #.##, and the user can enter more than two decimal places.

I would like to limit the input as the users types, so that he/she can only enter a max of two decimal places.

Best, -- Thomas


Solution

  • You have to implement a custom Validator and add it to the field:

                final ColumnConfig config = new ColumnConfig();
                config.setNumberFormat(NumberFormat.getFormat("#.##"));
                final NumberField field = new NumberField();
                field.setPropertyEditorType(Float.class); // needed to convert from String to Number - default ist Double
                field.setValidator(new com.extjs.gxt.ui.client.widget.form.Validator(){
                    public String validate(Field<?> field, String value) {
                        if(value != null){
                             final int index = value.indexOf('.');
                             if(index > -1 && index < value.length() - 3){
                                 return "Maximum number of digits is 2!";
                             }
                        }
                        return null;
                    }
                });
                final CellEditor cellEditor = new CellEditor(field);
                config.setEditor(cellEditor);