首页 > 解决方案 > 如何仅在 ExtJS 的文本字段中允许最多 3 位小数

问题描述

对于文本字段,我只需要允许它最多保留 3 个小数位。

允许的输入:123、123.1、123.34、123.458,但不应允许使用 123.4563。

我尝试了很多文章,但只找到了小数点后 2 位。

标签: extjsextjs7

解决方案


我不知道您为什么将文本字段用于数字字段。无论如何,这里是小数精度为 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());
                }
            }]
        });
    }
});

推荐阅读