【问题标题】:SimpleSchema custom validation message not showingSimpleSchema 自定义验证消息未显示
【发布时间】:2017-09-30 08:03:34
【问题描述】:

我正在尝试实现一个自定义验证函数,它可以返回true(如果该字段有效)或一些自定义错误消息。这是我目前的尝试:

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

这是一个人为的示例,但仍然无法正常工作。 custom 函数中的条件运行,当 true 返回时,记录会保存。但是,如果 "not contain a" 被返回,它不会成为客户端上显示的验证消息。它只是说content is invalid,我不确定如何自定义此消息。这是模板代码:

  {{#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}}

【问题讨论】:

    标签: javascript meteor coffeescript meteor-autoform simple-schema


    【解决方案1】:

    我的原始代码存在一些问题。

    首先,我没有具体说明我是如何要求SimpleSchema,但应该这样做;这使用了新的 node-simpl-schema 包,这是 meteor-simple-schema 迁移到的:

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

    验证消息映射到键:

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

    messagesen 哈希是正确结构所必需的。

    重点custom 的返回值不是在客户端显示的消息。它是一个,指向默认消息对象中的条目。

    例如:

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

    这将最终显示消息"doesnt contain a"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2018-02-08
      • 2021-10-20
      • 1970-01-01
      • 2019-02-22
      相关资源
      最近更新 更多