Search code examples
javascriptmeteormeteor-autoform

meteor autoform custom validation not reactive


I'm trying to use a custom validation function for a field defined in a simpleSchema, however the error message does not render on the field.

num: {
    type: Number,
    label: "Number",
    min: 1,
    decimal: false, // unnecessary as this is default for Number, but for future reference
    autoform: {
        group: "Info",
        defaultValue: function() {
            //@TODO - default to next number for logged in user
            return 5;
        }
    },
    custom: function () {
           Collection.simpleSchema().namedContext("addNumberForm").addInvalidKeys([{name: "num", type: "numNotUnique"}]);
    }
},

I've defined a custom error message for it

SimpleSchema.messages({numNotUnique: "This number has already been entered"});

When I submit the form I can confirm that the custom function executes, but nothing changes in the UI for that field indicating the error. The context name "addNumberForm" I got from the SimpleSchema.debug = true; setting and seeing what was thrown for other fields with default validation.

What am I missing here?


Solution

  • After much trial and error I've figured it out.

    The simpleSchema named context is only necessary if manually validating using simpleSchema by itself. Autoform takes care of this, and the custom function can return a simple string that defines the error.

    num: {
        type: Number,
        label: "Number",
        min: 1,
        decimal: false, // unnecessary as this is default for Number, but for future reference
        autoform: {
            group: "Info",
            defaultValue: function() {
                //@TODO - default to next number for logged in user
                return 5;
            }
        },
        custom: function () {
            // some check
            return 'numNotUnique'; // return our error
        }
    },