2015-10-11 99 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'); 
     } 

     } 
    } 
    } 
});