How to flag ngbDatepicker Valid on a form even if no values ​​are selected

I am using ng-bootstrap ngbDatepicker on Reactive Form in Angular2 project and dates are optional, however ngbDatepicker always marks the form as Invalid if no date is selected.

Is there a way to exclude ngbDatepicker from form validation or configure it to return Valid, whether it matters or not?

+3


source to share


2 answers


The problem was how I initialized the form values. I was setting default values ​​for empty strings where I had to initialize dates to zero. So I did this:

  replicantForm = this.fb.group({
      name: ['', Validators.required],
      incepdate: '',
      longevity: ''
  })

      

When I should have done this:



  replicantForm = this.fb.group({
      name: ['', Validators.required],
      incepdate: null,
      longevity: ''
  })

      

Many thanks to @ pkozlowski-opensource for the clarification.

+1


source


In response to the accepted answer and the fact that it won't work for future updates, I used the following hack to make sure the control is valid if no date is entered or the date is incorrect.

It's pretty frustrating to change the value in the validator if you ask me, but keep doing the job until ngb-datepicker sets the value internally.



Custom validator on the desired control:

validateOptionalDate(control: AbstractControl) {
  if (!(control.value instanceof Object) && control.value !== null) {
    control.patchValue(null, {
      onlySelf: true,
      emitEvent: false,
      emitModelToViewChange: true,
      emitViewToModelChange: false
    });
  }
}

      

+1


source







All Articles