简体   繁体   中英

Model validation errors in the Ext JS 5.0 framework

How can you get validation errors of a model, specifically in Ext JS 5.0 ? As in version 4.2 we did this:

var rec = Ext.create("ModelName", {...});
var errors = rec.validate();
if (!errors.isValid()) {
    form.markInvalid(errors);
}

However validate() is now marked as deprecated in the documentation and calling it no longer returns any error messages. I've looked at the getValidation() method which is introduced in 5.0 but it doesn't return any error messages which can be passed to a form component and there are no clear examples of how else to achieve this.

I've always had my configuration the other way around with the validators in the form itself - that way Ext.form.Panel isValid automatically marks the relevant fields as needed. It is fairly straight-forward to do what you want however with a few modifications - be forewarned though that getValidation returns a private utility class potentially making code susceptible to changes in future versions of the framework.

To start with, Ext.data.Model getValidation returns an instance of Ext.data.Validation which is notably a simple data-model itself. It is basically a key-value map of each field with corresponding validity - If a value is strictly boolean true then the field is valid, anything else ie a string (error message) then the field is invalid. For convenience, you could write a function that will return the errors in the format you need - in this example I've overridden the validation model itself but ideally you would incorporate the logic into your own models via extension or perhaps a mixin :

Ext.define('override.data.Validation', {
    override: 'Ext.data.Validation',
    getErrors: function(){
        var errors = [];
        Ext.iterate(this.getData(), function(field, value){
            if(true !== value) this.push({ id: field, msg: value });        
        }, errors);
        return errors;
    }    
});

Then modify your logic above as follows:

var rec = Ext.create("ModelName", { /***/ });
if(!rec.isValid()){
    form.markInvalid( rec.getValidation().getErrors() );
}

» demo / fiddle


It's also worth noting that if you are validating a model in this way the Presence validator always seems to return true (valid) regardless of whether or not you set a value - presumably because a defaultValue will exist on the record objects prototype? So I incorporated a custom validator into the demonstration:

Ext.define('validator.NotEmpty', {
    extend: 'Ext.data.validator.Validator',
    alias: 'data.validator.notempty',
    validate: function(value){
        return !Ext.isEmpty(value) || 'Field must not be empty';
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM