简体   繁体   中英

Angular(2/4/5/6) Custom validator error message not showing

I'm trying to get my validator to show up correctly using a form custom validator, but I'm not sure how to call it. I tried BroadcastForm.controls.errors.customTimeValidator() in the html side but it doesn't work correctly. Appreciate your help!

broadcast.component.ts

ngOnInit() {
    this.BroadcastForm = this.fb.group({
        datetime: [
            datetime,
            Validators.compose([Validators.required, this.customTimeValidator()]),
        ],
    });
}

customTimeValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } | null => {
        const minDate = new Date();
        minDate.setSeconds(0);
        this.minTime = minDate.getTime() + 59 * 1000;
        const forbidden = control.value <= minDate;
        return forbidden ? { forbiddenName: { value: control.value } } : null;
};
}

broadcast.component.html

<div class="validation-error" *ngIf="
   BroadcastForm.controls.datetimeOption.value === 'false' &&
   BroadcastForm.controls.errors.customTimeValidator()"> //how do I call customTimeValidator correctly?
   Please select a future date/time
 </div>

Change this

BroadcastForm.controls.errors.customTimeValidator()

to

BroadcastForm.controls['datetime']['errors']['forbiddenName']

Actually you could find all errors using json pipe

{{ BroadcastForm.controls['datetime']['errors'] | json }}

I'm sorry to say, the accepted answer is disgusting, both to look at and to use.

Use something simpler, cleaner, and documented :

BroadcastForm.get('datetime').hasError('forbiddenName')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM