[英]Meteor js: get full validation message with validatedmethod simpleschema
我是Meteor js的新手,我正在嘗試按照官方指南http://guide.meteor.com/methods.html#method-form創建表單。 建議使用基於mdg:validation-error的mdg:validated-method程序包和aldeed:simple-schema進行驗證,以將驗證錯誤消息返回給客戶端。 該指南建議使用此代碼,然后進行驗證
Invoices.methods.insert.call(data, (err, res) => {
if (err) {
if (err.error === 'validation-error') {
// Initialize error object
const errors = {
email: [],
description: [],
amount: []
};
// Go through validation errors returned from Method
err.details.forEach((fieldError) => {
// XXX i18n
errors[fieldError.name].push(fieldError.type);
});
// Update ReactiveDict, errors will show up in the UI
instance.errors.set(errors);
}
}
});
但是問題在於,err.error中僅提供fieldError.type,fieldError.name和簡單模式中的第一條人類可讀消息。 我在簡單模式中使用翻譯后的消息和字段標簽,以獲得很好的可理解的驗證錯誤消息。 因此,僅獲得帶有“ required”的對象屬性名稱是不可接受的,尤其是在消息包含最小/最大約束的情況下。 我找不到任何方法來獲取簡單模式的驗證上下文來檢索人類可讀錯誤的完整列表。
所以我的問題是我可以在客戶端上獲得完整的錯誤消息嗎? 或者,也許有更好的方法可以實現我的目標?
提前致謝
嗨! 最近我遇到了同樣的問題。 因此,我只是創建了具有一些代碼增強功能的拉取請求來解決此問題。 現在,當您提交表單並從客戶端調用validated-method
,如下所示:
yourMethodName.call(data, (err) => {
if (err.error === 'validation-error') {
console.dir(err, 'error ')
}
});
您將在console
看到error object
:
{
"errorType": "ClientError",
"name": "ClientError",
"details": [
{
"name": "firstName",
"type": "required",
"message": "First name is required"
},
{
"name": "lastName",
"type": "required",
"message": "Last name is required"
},
{
"name": "phone",
"type": "required",
"message": "Phone is required"
},
{
"name": "email",
"type": "required",
"message": "Email is required"
}
],
"error": "validation-error"
}
所以我只是從控制台輸出中復制它 。 就我而言,方法如下:
export const yourMethodName = new ValidatedMethod({
name: 'my.awesome.method',
validate: new SimpleSchema({
firstName: { type: String },
lastName: { type: String },
phone: { type: Number },
email: { type: String, regEx: SimpleSchema.RegEx.Email }
}).validator({ clean: true }),
run(doc) {
YourCollection.insert(doc);
}
});
如果我的請求將被接受,則可以輕松使用node-simple-schema (這是meteor-simple-schema的下一個版本)。 如果不能,你可以用我的叉子 。
希望這可以幫助!
編輯:現在此功能在官方的node-simple-schema 軟件包中可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.