2016-01-22 40 views
3

我有一個Meteor AutoForm集合架構,其中包含以下字段,我試圖讓它具有唯一性。它不允許在相同的情況下相同的值,但是當我更改大小寫的情況下,值被插入,所以如何防止插入具有不同大小寫的重複值?Meteor AutoForm中的唯一字段

TestTESTTesT所有具有相同的拼寫,所以它不應該插入。

我嘗試這樣做:

Schemas.Organisation = new SimpleSchema({ 
    company: { 
     type: String, 
     max: 200, 
     unique: true, 
     autoValue: function() { 
      if (this.isSet && typeof this.value === "string") { 
       return this.value.toLowerCase(); 
      } 
     }, 
     autoform:{ 
      label: false, 
      afFieldInput: { 
       placeholder: "Enter Company Name", 
      } 
     } 
    } 
    }) 

但它不會讓我插入重複的值,但將其轉換爲小寫,同時在數據庫中保存。那麼如何才能將用戶輸入的值保存下來,但值不應該有相同的拼寫?

回答

1

這可以通過使用自定義客戶端驗證來實現。如果你不希望你的Organisation集合中的所有文檔發佈到每一個客戶端,你可以使用一個asynchronous validation approach,例如:

Organisations = new Mongo.Collection("organisations"); 

Organisations.attachSchema(new SimpleSchema({ 
    company: { 
     type: String, 
     max: 200, 
     unique: true, 
     custom: function() { 
      if (Meteor.isClient && this.isSet) { 
       Meteor.call("isCompanyUnique", this.value, function(error, result) { 
        if (!result) { 
         Organisations.simpleSchema().namedContext("insertCompanyForm").addInvalidKeys([{ 
          name: "company", 
          type: "notUnique" 
         }]); 
        } 
       }); 
      } 
     }, 
     autoValue: function() { 
      if (this.isSet && typeof this.value === "string") { 
       return this.value.toLowerCase(); 
      } 
     }, 
     autoform: { 
      label: false, 
      afFieldInput: { 
       placeholder: "Enter Company Name", 
      } 
     } 
    } 
})); 

if (Meteor.isServer) { 
    Meteor.methods({ 
    isCompanyUnique: function(companyName) { 
     return Organisations.find({ 
     company: companyName.toUpperCase() 
     }).count() === 0; 
    } 
    }); 
} 

<body> 
    {{> quickForm collection="Organisations" id="insertCompanyForm" type="insert"}} 
</body> 

這裏有一個MeteorPad

+0

我偶然發現了這個,因爲我正在尋找一個針對_id的自定義驗證。我嘗試了上述方法,看起來在驗證錯誤發生後,我再次多次提交提交,似乎遇到了錯誤。服務器日誌說:異常時調用方法'/ aggrRouter_aaaContext_template_collection/insert'錯誤:名爲'isAggrUnique'的方法已經定義我已經打開了一個新的問題關於相同的[這裏](http://stackoverflow.com/questions/ 38481046 /自動窗體定製驗證-失敗-後多subsqeuent-的提交) – blueren