Skip to content

Instantly share code, notes, and snippets.

@mcelotti
Last active November 20, 2015 09:27
Show Gist options
  • Save mcelotti/fa7c16112735d36995e9 to your computer and use it in GitHub Desktop.
Save mcelotti/fa7c16112735d36995e9 to your computer and use it in GitHub Desktop.
Sencha Touch 2.4.2 override validate() to pass model and allow cross-field validation
Ext.define('MyApp.override.data.Model', {
override : 'Ext.data.Model',
/**
* @override
* we want to pass the model (not only config and value)
*/
validate : function() {
var errors = Ext.create('Ext.data.Errors'),
validations = this.getValidations().items,
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;
// here we go with the model
valid = validators[type](validation, this.get(field), this);
if (!valid) {
errors.add(Ext.create('Ext.data.Error', {
field : field,
message : validation.message || validators.getMessage(type)
}));
}
}
}
return errors;
}
});
@mcelotti
Copy link
Author

Why
This override is useful if you need to do some cross-field validations (ie a field is valid only if another field has a valid value)

Usage
First add this custom validator:

        Ext.applyIf(Ext.data.Validations, {
            custom : function(config) {
                return config.validator.apply(this, arguments);
            }
        });

Then add to model:

        validations : [{
            field : 'myfield',
            type : 'custom',
            message : 'your custom message',
            validator : function(config, value, model) {
                // do some validation and return true/false
            }
        }]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment