ExtJS – Optional model field with validation

In ExtJS 6.02 is it possible to have a field model that is optional but also has validation?

Example an email field that may or not be present but the email must be valid if it exists.

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

   identifier: {
      type      : 'sequential',
      seed      : 1,
      increment : 1
   },

   fields: [{
      name : 'date',
      type : 'date'
   }, {
      name : 'msg',
      type : 'string',
   }, {
      name : 'email',
      type : 'string',
   }],

   validators: {
      date: {
         type: 'presence'
      },
      msg: {
         type : 'length',
         min  : 2
      },
      email: {
         type : 'email'
      }
   }
});

Answer

You can override matcher of email validator to allow empty string:

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

    identifier: {
        type: 'sequential',
        seed: 1,
        increment: 1
    },

    fields: [{
        name: 'date',
        type: 'date'
    }, {
        name: 'msg',
        type: 'string',
    }, {
        name: 'email',
        type: 'string',
        allowBlank: true
    }],

    validators: {
        date: {
            type: 'presence'
        },
        msg: {
            type: 'length',
            min: 2
        },
        email: {
            type: 'email',
            // Override matcher to allow empty string
            matcher: /^$|^(")?(?:[^."])(?:(?:[.])?(?:[w-!#$%&'*+/=?^_`{|}~]))*1@(w[-w]*.){1,5}([A-Za-z]){2,6}$/
        }
    }
});

Ext.application({
    name: 'Fiddle',

    launch: function () {
        var myModel = Ext.create('my_model', {
            date: new Date(),
            msg: 'Some Message',
            //email: 'mustermann@gmail.com',
            email: '',
        });
        console.log(myModel.isValid());
    }
});