[英]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. 我正在尝试实现一个自定义验证功能,该功能可以返回
true
(如果字段有效)或某些自定义错误消息。 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. 运行
custom
函数中的条件,并在返回true
时保存记录。 However, if "not contain a"
gets returned, it does not become the validation message displayed on the client. 但是,如果返回
"not contain a"
,则它不会成为客户端上显示的验证消息。 It just says content is invalid
, and I'm not sure how to customize this message. 它只是说
content is invalid
,而且我不确定如何自定义此消息。 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}}
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; 首先,我没有指定我需要
SimpleSchema
但是应该通过这种方式完成; this uses the new node-simpl-schema
package which is what meteor-simple-schema
migrated to: 它使用了新的
node-simpl-schema
包,这是meteor-simple-schema
迁移到的包:
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. 该
messages
和en
哈希值是必要的它是正确的结构。
important point : the return value of custom
is not the message that gets displayed on the client. 要点 :
custom
的返回值不是在客户端上显示的消息。 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"
这将最终显示消息
"doesnt contain a"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.