Search code examples
javascriptvalidationextjsmodel

ExtJS - Model field with mixed value types


In ExtJS 6.2, how can I define a model field which can be of different values, for example, string or boolean and validate that it can either be true, false or a string?

In the bellow model the value can be either a string or boolean.

Ext.define('my_model', {
   extend  : 'Ext.data.Model',

   fields: [{
      name   : 'name',
      type   : 'string',
      unique : true
   }, {
      name : 'value',
      convert(value) {
         switch (value) {
            case 'Y': return true;
            case 'N': return false;
            default : return value;
         }
      }
   }],

   validators: {
      value: {
         // How do I validate it?
      }
   }
});

Solution

  • You can use auto field and validate property:

    Ext.define('my_model', {
        extend: 'Ext.data.Model',
    
        fields: [{
            name: 'name',
            type: 'string',
            unique: true,
        }, {
            name: 'value',
            type: 'auto',
            convert(value) {
                switch (value) {
                case 'Y':
                    return true;
                case 'N':
                    return false;
                default:
                    return value;
                }
            },
            validate: function (value) {
                return ['boolean', 'string'].indexOf(typeof value) !== -1;
            }
        }]
    });
    
    Ext.application({
        name: 'Fiddle',
    
        launch: function () {
            var myModel = Ext.create('my_model', {
                name: 'Some name',
                value: 'N'
            });
            console.log(myModel.getData());
            console.log(myModel.isValid());
        }
    });