Archive

Posts Tagged ‘cross field’

Cross field model validation in extjs4

I dont see an easy way to make validations where one field depends on another. I think they must have forgotten to support it. What is missing is the model instance passed to the validation method. Now it looks like this:
    function(config, value)
and we would like it to look like this
    function(config, value, model)
, then we would have access to all fields.

But we just need to override Ext.data.Model.validate() and pass the model instance to the validation function as an extra parameter:

valid = validators[type](validation, this.get(field), this);

Ext.override(Ext.data.Model, {
    validate: function() {
        var errors = Ext.create('Ext.data.Errors'),
                validations = this.validations,
                validators = Ext.data.validations,
                length, validation, field, valid, type, i;

        if (validations) {
            length = validations.length;

            for (i = 0; i < length; i++) {
                validation = validations[i];
                field = validation.field || validation.name;
                type = validation.type;
                valid = validators[type](validation, this.get(field), this);

                if (!valid) {
                    errors.add({
                        field  : field,
                        message: validation.message || validators[type + 'Message']
                    });
                }
            }
        }

        return errors;
    }
});

Now we have access to the model instance:

Ext.data.validations.range = function(config, value, model) {
    ....
    var someValue = model.get('someField')
    ....
}
Advertisements