Angular-如何在issuedDate和expiryDate之间进行验证



我正在Angular-14中实现ngx引导日期选择器。然后我想在驾驶执照的签发日期和到期日期之间进行验证。

我有这个代码。

组件.ts:

minIssuedDate!: Date;
minExpiryDate!: Date;
constructor(
private fb: FormBuilder
) {
this.minIssuedDate = new Date();
this.minExpiryDate = new Date();
this.minIssuedDate.setDate(this.minIssuedDate.getDate());
this.minExpiryDate.setDate(this.minExpiryDate.getDate() + 1);
}
createProfile() {
this.createProfileForm = this.fb.group({
issuedDate: ['', [Validators.required],
expiryDate: ['', [Validators.required]]
});
}
ngOnInit(): void {
this.createProfile();
}

component.html:

<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="issuedDate">Issued Date</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
</div>
<input type="text"
placeholder="DD-MM-YYYY"
class="form-control"
formControlName='issuedDate'
bsDatepicker
[minDate]="minIssuedDate"
[bsConfig]="{ isAnimated: true, dateInputFormat: 'DD-MM-YYYY', returnFocusToInput: true, showClearButton: true, clearPosition: 'right' }">
</div>
<div *ngIf="fc['issuedDate'].touched && fc['issuedDate'].invalid" class="alert alert-danger">
<div *ngIf="fc['issuedDate'].errors && fc['issuedDate'].errors['required']">Issued Date field is required!</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="expiryDate">Expiry Date<span style="color:red;">*</span></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
</div>
<input type="text"
placeholder="DD-MM-YYYY"
class="form-control"
formControlName='expiryDate'
bsDatepicker
[minDate]="minExpiryDate"
[bsConfig]="{ isAnimated: true, dateInputFormat: 'DD-MM-YYYY', returnFocusToInput: true, showClearButton: true, clearPosition: 'right' }">
</div>
<div *ngIf="fc['expiryDate'].touched && fc['expiryDate'].invalid" class="alert alert-danger">
<div *ngIf="fc['expiryDate'].errors && fc['expiryDate'].errors['required']">Expiry Date field is required!</div>
</div>
</div>
</div>
</div>

如何验证issuedDate不得大于ExpiryDate?

感谢

您可以创建一个自定义验证器并将其应用于createProfileForm

Ts

createProfile() {
this.createProfileForm = this.fb.group(
{
issuedDate: ['', [Validators.required]],
expiryDate: ['', [Validators.required]],
},
{ validators: this.dateValidator }
);
}
dateValidator(group: FormGroup): ValidationErrors | null {
const fromCtrl = group.get('issuedDate')!;
const toCtrl = group.get('expiryDate')!;
return new Date(fromCtrl.value) > new Date(toCtrl.value)
? { issueDateGreater: 'issue date is greater than expiry date' }
: null;
}

Html

<span *ngIf="createProfileForm!.hasError('issueDateGreater')">issue date is greater than expiry date</span>

相关内容

  • 没有找到相关文章

最新更新