extjsextjs7

How to allow upto 3 decimal places only in textfield in ExtJS


For a textfield I need to allow it upto 3 decimal places only.

Allowed inputs : 123, 123.1, 123.34, 123.458 but 123.4563 should not be allowed.

I tried so many articles but found upto 2 decimal places only.


Solution

  • I don't know why are you using textfield for number field. Anyway, here is fiddle code for text field and number field with decimal precision 3.

    Ext.application({
        name: 'Fiddle',
    
        launch: function () {
            Ext.create('Ext.form.Panel', {
                title: "Form Panel",
                width: 300,
                renderTo: Ext.getBody(),
                layout: 'form',
                items: [{
                    xtype: 'numberfield',
                    name: 'bottles',
                    fieldLabel: 'Number Field',
                    decimalPrecision: 3 // This will allow only 3 decimal places.. 
                }, {
                    xtype: 'textfield',
                    name: 'name',
                    fieldLabel: 'Text Field',
                    maskRe: /[0-9.-]/,
                    //regex: /^-?[0-9]*(\.[0-9]{1,3})?$/, // Without error message
                    validator: function (v) { // With error Message
                        return /^-?[0-9]*(\.[0-9]{1,3})?$/.test(v) ? true : 'Max. decimal precision is 3';
                    },
                }],
                buttons: [{
                    text: "Show Form Values",
                    handler: function() {
                        console.log(this.up('form').getValues());
                    }
                }]
            });
        }
    });