将您的 maskRe 更改为
maskRe: /[0-9.-]/,
validator: function(v) {
return /^-?[0-9]*(\.[0-9]{1,2})?$/.test(v)? true : 'Only positive/negative float (x.yy)/int formats allowed!';
},
关键是您允许使用maskRe 的一些字符(而不是值本身)并验证validator 中的字符串输入。
模式详情:
-
^ - 字符串开头
-
-? - 可选连字符
-
[0-9]* - 零个或多个数字
-
(\.[0-9]{1,2})? - 可选序列
-
\. - 一个点
-
[0-9]{1,2} - 任意 1 位或 2 位数字
-
$ - 字符串结束。
更新
如果输入值与正则表达式不匹配,您可以强制恢复为以前的值。请参阅下面的完整 sn-p:
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.create('Ext.form.Panel', {
title: 'maskRe',
width: 600,
bodyPadding: 10,
renderTo: Ext.getBody(),
items: [{
xtype: 'textfield',
fieldLabel: 'Enter Postive or Negative integer or decimal No.',
width : 600,
labelWidth : 300,
anchor: '100%',
maskRe: /[0-9.-]/,
validator: function(v) {
return /^-?[0-9]*(\.[0-9]{1,2})?$/.test(v)? true : 'Only positive/negative float (x.yy)/int formats allowed!';
},
listeners: {
change: function(e, text, prev) {
if (!/^-?[0-9]*(\.[0-9]{0,2})?$/.test(text))
{
this.setValue(prev);
}
}
}
}],
});
}
});
change 事件被添加到字段 listeners 中,如果值与 /^-?[0-9]*(\.[0-9]{0,2})?$/ 正则表达式不匹配(类似于验证正则表达式,但允许后面没有数字的点以允许进一步输入),则使用this.setValue(prev) 还原值。