2015-10-11 100 views
3

我有以下模式:驗證日期值

Dates.attachSchema(new SimpleSchema({ 
    description: { 
     type: String, 
     label: "Description", 
     max: 50 
    }, 
    start: { 
     type: Date, 
     autoform: { 
      afFieldInput: { 
       type: "bootstrap-datepicker" 
      } 
     } 
    }, 
    end: { 
     type: Date, 
     autoform: { 
      afFieldInput: { 
       type: "bootstrap-datepicker" 
      } 
     } 
    } 
})); 

我如何可以驗證end日期不start過嗎?我使用MomentJS來處理日期類型,但是我的主要問題是我如何訪問custom函數中的其他屬性。

例如:

end: { 
    type: Date, 
    autoform: { 
     afFieldInput: { 
      type: "bootstrap-datepicker" 
     } 
    }, 
    custom: function() { 
     if (moment(this.value).isBefore(start)) return "badDate"; 
    } 
} 

如何訪問start

此外,我怎麼能驗證,如果start + end日期組合獨特,意思是沒有保存在我的數據庫文件,該文件具有完全相同的startend日期?

回答

2

對於場間的溝通,你可以這樣做:

end: { 
    type: Date, 
    autoform: { 
    afFieldInput: { 
     type: "bootstrap-datepicker" 
    } 
    }, 
    custom: function() { 
    // get a reference to the fields 
    var start = this.field('start'); 
    var end = this; 
    // Make sure the fields are set so that .value is not undefined 
    if (start.isSet && end.isSet) { 
     if (moment(end.value).isBefore(start.value)) return "badDate"; 
    } 
    } 
} 

你當然應該申報badDate錯誤第一

SimpleSchema.messages({ 
    badDate: 'End date must be after the start date.', 
    notDateCombinationUnique: 'The start/end date combination must be unique' 
}) 

關於獨特性,首先簡單模式的本身不提供唯一性檢查。你應該爲此添加aldeed:collection2

此外,collection2只能檢查單個字段唯一性。爲了實現複合索引,你應該甚至在此之後使用ensureIndex語法

Dates._ensureIndex({ start: 1, end: 1 }, { unique: true }) 

,你將無法看到錯誤從表單上這個複合索引,因爲自動窗體需要知道,這樣的錯誤是存在的。

AutoForm.hooks({ 
    NewDatesForm: { // Use whatever name you have given your form 
    before: { 
     method: function(doc) { 
     var form = this; 
     // clear the error that gets added on the previous error so the form can proceed the second time 
     form.removeStickyValidationError('start'); 
     return doc; 
     } 
    }, 
    onSuccess: function(operation, result, template) { 
     if (result) { 
     // do whatever you want if the form submission is successful; 
     } 
    }, 
    onError: function(operation, error) { 
     var form = this; 
     if (error) { 

     if (error.reason && error.reason.indexOf('duplicate key error')) { 
      // We add this error to the first field so it shows up there 
      form.addStickyValidationError('start', 'notDateCombinationUnique'); // of course you have added this message to your definition earlier on 
      AutoForm.validateField(form.formId, 'start'); 
     } 

     } 
    } 
    } 
});