我正在嘗試添加驗證,以便結束日期不能在開始日期之前。不幸的是,我不知道該怎麼做,到目前爲止我還沒有在互聯網上找到有用的建議。我的形式如下:Angular 2表單驗證開始日期> =結束日期
editAndUpdateForm(tageler: Tageler) {
this.tageler = tageler;
this.tagelerForm = this.fb.group({
title: [this.tageler.title, Validators.required],
text: this.tageler.text,
group: [[this.tageler.group], Validators.required],
date_start: new Date(this.tageler.start).toISOString().slice(0, 10),
date_end: new Date(this.tageler.end).toISOString().slice(0, 10),
...
});
this.tagelerForm.valueChanges
.subscribe(data => this.onValueChanged(data));
}
我的驗證至今:
onValueChanged(data?: any) {
if (!this.tagelerForm) {
return;
}
const form = this.tagelerForm;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
validationMessages = {
'title': {
'required': 'Geben Sie bitte einen Namen ein.',
},
'group': {
'required': 'Wählen Sie bitte eine Gruppe aus.'
},
'bringAlong': {
'required': 'Bitte Feld ausfüllen.'
},
'uniform': {
'required': 'Bitte Feld ausfüllen.'
},
};
formErrors = {
'title': 'Geben Sie bitte einen Namen ein.',
'group': 'Wählen Sie bitte eine Gruppe aus.',
'bringAlong': 'Bitte Feld ausfüllen',
'uniform': 'Bitte Feld ausfüllen',
};
的表單控件的DATE_START「&「DATE_END」包含「形式的日期字符串dd.MM. yyyy',我希望'date_end'大於或等於'date_start'。
我想直接顯示錯誤信息(我的HTML代碼如下所示:)
<label for="formControlName_date_end" class="col-3 col-form-label">Ende:</label>
<div class="col-5">
<input id="formControlName_date_end" class="form-control" formControlName="date_end" type="date" value="{{tageler.end | date: 'yyyy-MM-dd'}}">
</div>
<div *ngIf="formErrors.date_end" class="alert alert-danger">
{{ formErrors.date_end }}
</div>
有人能幫助我嗎?
謝謝!
非常感謝您sainu,這完美的作品! :) – Ramona
可以請你把它標記爲答案@Ramona – sainu
雖然它顯示錯誤消息表單驗證仍然返回「有效」是否有一種方法來影響真正的形式驗證? – alex