2015-10-11 2 views
3

У меня есть следующие схемы:Validate значения даты в Метеор AutoForm SimpleSchema

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 даты уникального, то есть не сохраняется в моей базе данных документа, который имеет точно такое же start и end дату?

ответ

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 должен знать, что такая ошибка существует.

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'); 
     } 

     } 
    } 
    } 
}); 
Смежные вопросы