簡體   English   中英

如何在sencha touch / ext js模型中編寫驗證

[英]how to write validation in sencha touch / ext js model

我有這樣的模特

Ext.define('app.model.TeamEmpAssignment', {
            extend : 'Ext.data.Model',
            config : {
                idProperty : 'teamEmpId',
                fields : [{
                        name : 'teamEmpId',
                        type : 'int'
                    }, {
                        name : 'actName'
                    }, {
                        name : 'beginDateTime'
                    }, {
                        name : 'endDateTime'
                    },

                ],

                validations : [{
                        field : 'beginDateTime',
                        type : 'presence',
                        message : 'Effective Begin Date Time required'
                    }, {
                        field : 'endDateTime',
                        type : 'presence',
                        message : 'Effective End Date Time required'
                    },
                ],

            }

        });

我必須編寫一個驗證以比較endDateTime> startDateTime

我正在嘗試sencha touch 2.3.1

我知道這是一個老問題,但是我在處理相同問題時遇到了這個問題,並希望分享我的方法。

我在模型中創建了一個方法,用於進行自定義驗證,類似於:

Ext.define('app.model.TeamEmpAssignment', {
    extend : 'Ext.data.Model',
    config : {
        // config here
    },

    checkDates: function (errors) {
        // assuming the dates are timestamps
        if (this.get('beginDateTime') > this.get('endDateTime')) {
            errors.add(Ext.create('Ext.data.Error', {
                field  : 'beginDateTime',
                message: 'Begin date can\'t be after end date'
            }));
        }
    }

});

您會注意到checkDates有一個參數-錯誤。 此參數實際上是模型的validate方法返回的Ext.data.Errors對象。 因此,我們可以執行以下操作:

var record = Ext.create('Ext.data.Errors');
// set some values here
var errors = record.validate();
record.checkDates(errors);

console.log(errors.isValid());

我們可以使用isValid,因為它所做的只是檢查Ext.data.Errors集合中是否包含項。

我目前正在這樣使用它,但是重寫validate方法非常容易,因此您不必外部調用自定義驗證。

Ext.define('app.model.TeamEmpAssignment', {
    extend : 'Ext.data.Model',
    config : {
        // config here
    },

    checkDates: function (errors) {
        // assuming the dates are timestamps
        if (this.get('beginDateTime') > this.get('endDateTime')) {
            errors.add(Ext.create('Ext.data.Error', {
                field  : 'beginDateTime',
                message: 'Begin date can\'t be after end date'
            }));
        }
    },

    validate: function () {
        var errors = this.callParent(arguments);

        this.checkDates(errors);

        return errors;
    }

});

驗證類型來自Ext.data.validations單例。 您可以在此處添加自己的驗證器,但是該方法不能提供模型中的所有字段(聽起來像您需要的)。 我們建議將驗證器移動到模型外部的其他位置(可能在相關表單組件上)(在加載之后或保存之前)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM