Set dynamic Validator with Angular 16

23 views Asked by At

I'm looking to define a dynamic validator for my project. For this I use the FormControl object, the SetValidators() and updateValueAndValidity() methods which return a null value and this is what causes the problem because if my input is null, Angular return me a 500 error.

  ngOnInit(){
    this.reactiveForm = this.formBuilder.group({
      dateStart: [this.currentDateStart],
      dateEnd: [this.currentDateEnd],
      motif: new FormControl(null),
      // motif: new FormControl(this.currentMotif),
      label: [this.currentLabel],
      type: [this.currentType],
      status: [this.currentStatus],
    });
  }

My method for updating my Validator

  isMotifRequired(e:any): any {
    let selectedValue = e.target.value;
    
    if (selectedValue === this.absenceType.UNPAID_LEAVE) {
      this.reactiveForm.controls["motif"].setValidators([Validators.required]);
      console.info("Validator OK");
    }else{
      this.reactiveForm.controls["motif"].setValidators(null);
      console.info("Validator NOT OK");
    }
    this.reactiveForm.controls["motif"].updateValueAndValidity();
  }

My goal is to make the "pattern" entry mandatory if absenceType takes a certain value. The problem here is that the null value for the validator works but when submitting the form it gives me an error because the null value is not accepted in the backend; and leaving a value "" works but in this case my control no longer works, the pattern can be submitted freely without conditions...

I tried to change the structure of my object to also be null and I also tried to change the null to " " in the service but I still got the same error.

0

There are 0 answers