Krishnan
Krishnan

Reputation: 1050

How to display Custom Validation error message using "app-form-group-control-validation-display" in angular 4

We are using FormBuilder, FormGroup, Validators, FormControl to check and display validations. For date validation I have used Custom validation. For this I have created a validation directive DateTypeValidationDirective. Please see the below code snippet.

import { Directive, Input } from "@angular/core";
import { NG_VALIDATORS, Validator, AbstractControl, ValidatorFn } from "@angular/forms";
import * as moment from "moment";

@Directive({
    selector: '[date]',
    providers: [{ provide: NG_VALIDATORS, useExisting:
                DateTypeValidatorDirective, multi: true }]

})

export class DateTypeValidatorDirective implements Validator {
    @Input() dDate: Date;
    validate(control: AbstractControl): { [key: string]: any } {
        return this.dDate ? this.dateTypeValidator()(control)
            : null;
    }
    dateTypeValidator(): ValidatorFn {
        return (control: AbstractControl): { [key: string]: any } => {
            const valid = control.value == '' || moment(moment(control.value).format("l LT"), ["l LT"], true).isValid() 

            if (!valid) {
                return {
                      'dateType': { value: "invalid date" }
                }; 
            }    
         };
   }
}

In component I have used the below code snippet

ngOnInit(): void {
     this.formGroupCore = this.formBuilder.group({

     dueDate: new FormControl("", 
     [this.dateTypeValidatorDirective.dateTypeValidator()])
    });
}

In html file written the below code

<input id="dueDate" type="date" formControlName="dueDate" 
            class="form-control form-control-sm" />

<app-form-group-control-validation-display
    *ngIf="formGroupCore.get('dueDate').hasError(error)" 
    [formGroup]="formGroupCore" [propertyName]="'dueDate'" >invalid date
</app-form-group-control-validation-display>

The validation is working fine but error message is not displaying. How to set the error message?

Please anyone help to achieve the same

Upvotes: 2

Views: 2181

Answers (1)

Krishnan
Krishnan

Reputation: 1050

I have tried with the below code snippet and the validation works fine.

<app-form-group-control-validation-display  [formGroup]="formGroupCore" [propertyName]="'dueDate'" [custom]="[{'dateType':'Please enter a valid date'}]">
                            </app-form-group-control-validation-display>  

Upvotes: 1

Related Questions