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日付の組み合わせが一意であるかどうかを検証するにはどうすればよいですか?つまり、データベースにまったく同じ日付のドキュメントが保存されていないことを意味startします。end

4

1 に答える 1

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 は 1 つのフィールドの一意性のみをチェックできます。複合インデックスを実現するには、次の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');
        }

      }
    }
  }
});
于 2015-10-27T23:28:51.570 に答える