我在ExtJS中有颜色选择器,我用它来选择颜色作为背景。但是我希望用户能够输入他们自己的HEX代码。为了确保他们没有将无效的十六进制代码放入字段,我想验证他们是否有适当数量的字符。
用户还可以输入名称颜色,如:黑色,红色,metalbrightblue。
The SenchaDocumentation on validators was.. Less than helpful.
validator: function (val) {
// remove non-numeric characters
var tn = val.replace(/[^0-9]/g,''),
errMsg = "Must be a 10 digit telephone number";
// if the numeric value is not 10 digits return an error message
return (tn.length === 10) ? true : errMsg;
}
一旦我尝试使用自定义验证器,我的颜色选择器就会消失。有人能给我一个更全面的使用验证器的指南吗?感谢。
修改
我在ExtJS
的Selector源代码上的扩展.js文件Ext.define('name.name.colorpick.Selector', {
extend: 'Ext.ux.colorpick.Selector',
xtype: 'xtype-xtype-colorpick-selector',
editable:false,
getSliderAndAField: function() {
return [];
},
getMapAndHexRGBFields: function(){
var me = this;
var result = this.callParent(arguments);
var hexField = result.items[1].items[0];
hexField.disabled = true;
hexField.listeners = {
change: function(field,value){
me.setValue(value);
}
};
return result;
},
getSliderAndHField: function (){
var me = this;
var result = this.callParent(arguments);
var hField = result.items[1];
hField.disabled = true;
return result;
},
getSliderAndSField: function (){
var me = this;
var result = this.callParent(arguments);
var sField = result.items[1];
sField.disabled = true;
return result;
},
getSliderAndVField: function (){
var me = this;
var result = this.callParent(arguments);
var vField = result.items[1];
vField.disabled = true;
return result;
}
});
答案 0 :(得分:1)
基于Validating css color names,您可以在此处定义hex字段的验证器。我假设您希望hexField可以编辑。
getMapAndHexRGBFields: function (childViewModel) {
var me = this;
var result = this.callParent(arguments);
var hexField = result.items[1].items[0];
hexField.readOnly = false;
hexField.validator= function (val) {
var validateColor = function(stringToTest) {
if (stringToTest === "") {
return false;
}
if (stringToTest === "inherit") { return false; }
if (stringToTest === "transparent") { return false; }
var image = document.createElement("img");
image.style.color = "rgb(0, 0, 0)";
image.style.color = stringToTest;
if (image.style.color !== "rgb(0, 0, 0)") { return true; }
image.style.color = "rgb(255, 255, 255)";
image.style.color = stringToTest;
return image.style.color !== "rgb(255, 255, 255)";
};
var isValid = validateColor(val);
var errMsg = "Not a valid Color";
return isValid ? true : errMsg;
};
hexField.listeners = {
change: function(field, value){
if(field.isValid()) {
me.setValue(value);
}
}
};
return result;
}