一个ext自动格式化金额的控件

来源:互联网 发布:charls数据 编辑:程序博客网 时间:2024/06/05 23:47

/**
* 参考Datefield实现了CnMoneyField,继承自numberField,可以实现格式化金额数字(中文金额)
*
* @class Ext.form.CnMoneyField
* @extends Ext.form.NumberField
*/
Ext.form.CnMoneyField = Ext.extend(Ext.form.NumberField, {
// 运行输入的字符集
baseChars : "0123456789¥,",
// private
initEvents : function() {
Ext.form.NumberField.superclass.initEvents.call(this);
var allowed = this.baseChars + '';
if (this.allowDecimals) {
allowed += this.decimalSeparator;
}
if (this.allowNegative) {
allowed += "-";
}
this.stripCharsRe = new RegExp('[^' + allowed + ']', 'gi');
var keyPress = function(e) {
var k = e.getKey();
if (!Ext.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)) {
return;
}
var c = e.getCharCode();
if (allowed.indexOf(String.fromCharCode(c)) === -1) {
e.stopEvent();
}
};
this.el.on("keypress", keyPress, this);
},

// private
validateValue : function(value) {
if (!Ext.form.NumberField.superclass.validateValue.call(this, value)) {
return false;
}
if (value.length < 1) { // if it's blank and textfield didn't
// flag it then it's valid
return true;
}
var re = /,/g;
value = String(value).replace(re, '');
value = String(value).replace('¥', '');
value = String(value).replace(this.decimalSeparator, ".");
if (isNaN(value)) {
this.markInvalid(String.format(this.nanText, value));
return false;
}
var num = this.parseValue(value);
if (num < this.minValue) {
this.markInvalid(String.format(this.minText, this.minValue));
return false;
}
if (num > this.maxValue) {
this.markInvalid(String.format(this.maxText, this.maxValue));
return false;
}
return true;
},

getValue : function() {
return this.parseValue(Ext.form.NumberField.superclass.getValue.call(this));
},

setValue : function(v) {
Ext.form.NumberField.superclass.setValue.call(this, v);
},

// private
parseValue : function(value) {
var re = /,/g;
value = String(value).replace(re, '');
value = String(value).replace('¥', '');
value = parseFloat(String(value).replace(this.decimalSeparator, "."));
return value;
},

// private
fixPrecision : function(value) {
var nan = isNaN(value);
if (!this.allowDecimals || this.decimalPrecision == -1 || nan || !value) {
return nan ? '' : value;
}
return parseFloat(parseFloat(value).toFixed(this.decimalPrecision));
},

beforeBlur : function() {
var v = this.parseValue(this.getRawValue());
v = this.cnMoney(v);
if (v) {
this.setValue(v);
}
},
cnMoney : function(v) {
v = (Math.round((v - 0) * 100)) / 100;
v = (v == Math.floor(v)) ? v + ".00" : ((v * 10 == Math.floor(v * 10))
? v + "0"
: v);
v = String(v);
var ps = v.split('.');
var whole = ps[0];
var r = /(/d+)(/d{3})/;
while (r.test(whole)) {
whole = whole.replace(r, '$1' + ',' + '$2');
}
if (this.allowDecimals) {
var sub = ps[1] ? '.' + ps[1] : '.00';
v = whole + sub;
} else {
v = whole;
}
if (v.charAt(0) == '-') {
return '-¥' + v.substr(1);
}
return "¥" + v;
}
});
Ext.reg('cnMoneyfield', Ext.form.NumberField);