mic*_*mcg 10 javascript validation extjs sencha-touch
Sencha的这篇文章介绍了如何使用内置的验证规则(存在,长度,格式,包含,排除),并提到添加自定义规则很容易,但是没有解释如何去做.我已经googled高低,并阅读了sencha文档,但我找不到任何关于如何做到这一点.有任何想法吗?
http://www.sencha.com/learn/using-validations-and-associations-in-sencha-touch
我认为这是文档中的一个小错误.我通过添加一些代码让他们工作
if (Ext.data) {
Ext.data.validations.custom = function (config, value) {
if (config && Ext.isFunction(config.fn)) {
//this should be the model
if (config.self) {
return config.fn.call(config.self, value);
} else {
return config.fn(value);
}
}
else
{
return false;
}
};
Ext.data.validations.customMessage = "Error";
}
Run Code Online (Sandbox Code Playgroud)
然后,为模型添加验证,将对象添加到模型的验证数组中,类型设置为'custom',例如
{
type: 'custom', field: 'SomeField', message: "Your field is bad",
fn: function (SomeFieldValueForThisInstance) {
//Add some validation code. The this pointer is set to the model object
//so you can call this.get("SomeOtherFieldToCheck")
//or any other instance method
//if the field is good
return true;
//else
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
更新: @salgiza是对的,我忘了提几个步骤,以正确设置'this'指针.如果您查看sencha触摸代码,您将看到在Ext.data.Model的构造函数的末尾,它会检查是否在对象上定义了init函数,如果是,则调用它
if (typeof this.init == 'function') {
this.init();
Run Code Online (Sandbox Code Playgroud)
定义模型后,可以向原型添加init函数.在该函数中,迭代对象的验证并添加对此的引用.此步骤应在创建任何模型之前完成.
YourModel.prototype.init = function () {
var i, len;
if (this.validations) {
for (i = 0, len = this.validations.length; i < len; i++) {
this.validations[i].self = this;
}
}
};
Run Code Online (Sandbox Code Playgroud)
然后在上面的自定义验证函数中,只检查配置是否有自我指针,如果有,请用self调用它.我编辑了上面的代码来使用self.
注意:我没有看到模型的init函数被记录,所以如果sencha摆脱它,你将不得不以其他方式将this指针添加到模型的验证中.
对不起,如果这给任何人造成了混乱.
| 归档时间: |
|
| 查看次数: |
7239 次 |
| 最近记录: |