Search code examples
javascriptmeteorcoffeescriptmeteor-autoformsimple-schema

SimpleSchema custom validation message not showing


I am trying to implement a custom validation function which can return either true (if the field is valid) or some custom error message. Here's my current attempt:

global.Messages = Models.Messages = new Mongo.Collection 'messages'

MessagesSchema = new SimpleSchema({
  content: {
    type: String,
    label: "Message",
    max: 200,
    custom: ->
      if @obj.content.includes("a")
        true
      else
        "not contain a"
}, {tracker: Tracker})

Messages.attachSchema MessagesSchema

This is a contrived example but still, it's not working. The conditional in the custom function is run, and when true gets returned then the record does save. However, if "not contain a" gets returned, it does not become the validation message displayed on the client. It just says content is invalid, and I'm not sure how to customize this message. Here's the template code:

  {{#autoForm collection="Messages" id="insertMessageForm" type="insert"}}
    <fieldset>
      <legend>Add message</legend>
      {{> afFieldInput type='text' name='content'}}
      {{#if afFieldIsInvalid name='content'}}
      <span class="help-block">{{afFieldMessage name='content'}}</span>
      {{/if}}
    </fieldset>
    <button type='submit' class='btn btn-primary'>Insert</button>
  {{/autoForm}}

Solution

  • There were a few problems with my original code.

    First of all, I didn't specify how I was requiring SimpleSchema but it should be done this way; this uses the new node-simpl-schema package which is what meteor-simple-schema migrated to:

    SimpleSchema = require('simpl-schema').default
    SimpleSchema.extendOptions(['autoform']);
    

    Validation messages are mapped to keys:

    SimpleSchema.setDefaultMessages
      messages:
        en: 
          "notA": "doesnt contain a"
    

    The messages and en hashes are necessary for it to be the correct structure.

    important point: the return value of custom is not the message that gets displayed on the client. It is a key, pointing to the entry in the default messages object.

    For example:

    custom: ->
      if @obj.content.includes("a")
        true
      else
        "notA"
    

    This will end up showing the message "doesnt contain a"