0
votes

I have a form like below

this.personForm = new FormGroup({
            title: new FormControl(this.person.salutation, Validators.compose([
            Validators.minLength(2)
        ])),
            firstName: new FormControl(this.person.firstName, Validators.compose([
            Validators.minLength(4)
        ])),
});

Based on a configuration from an API call I want to make them dynamically required or not. I know I can use formControl.setValidators([Validators.required]) but that will clear existing Validators.

I was hoping to achieve it in one of the following ways

  • A function for just adding (Exp: addValidators([]))
  • OR a function that would give me the list of Validators a formControl already has, so that I can join them with what I want to add. (Exp: getValidators())

Unfortunately(as for as I know) none of above 2 functions exist. So how can one add a new Validation to a formControl without having to know already existing ones?

1
Can you please share your server validation json - Ajay Ojha
@AjayOjha this is all front-end, what server validation do you mean? The API will just give me an array of booleans that will let me know whether to make formControls required or not. The rest is all Front-End - Herbi Shtini
I thought dynamic rules are coming from server, now understood, based on which condition you want to apply required? - Ajay Ojha
@AjayOjha That part is just business logic, don't get confused with that. For simplicity consider just this: how can I add an additional Validation to title after form is inited but without losing old Validations (In this case Validator.minLength(2))?. Thanks - Herbi Shtini
please refer this provided link for conditionally required validation rxweb.io/validation-validators/required#conditionalexpression and please let me if this doesn't fulfil your need. - Ajay Ojha

1 Answers

2
votes

I supouse you can use a customValidator that depends of one variable, In the example, a button make a variable "yet" true or false. depending the form is valid or not

@Component({
  selector: 'my-app',
  template:`
  <form [formGroup]="personForm">
     <input formControlName="title"/>
     <input formControlName="firstName"/>
  </form>
  <button (click)="addValidator()">click</button>
  <hr/>
  {{personForm?.errors|json}}
  {{personForm?.valid}}`
})
export class AppComponent implements OnInit {
  yet: boolean;
  personForm: FormGroup;
  person = { salutation: "", firstName: "" }
  ngOnInit() {
    this.personForm = new FormGroup({
      title: new FormControl(this.person.salutation, Validators.compose([
        Validators.maxLength(2)
      ])),
      firstName: new FormControl(this.person.firstName, Validators.compose([
        Validators.minLength(4)
      ])),
    }, this.customValidator())
  }
  addValidator() {
    this.yet = !this.yet;
    this.personForm.updateValueAndValidity();
  }
  customValidator() {
    return (group: FormGroup) => {
      if (!this.yet)
        return null;
      if (group.get('title').value == '')
        return { title: 'required' }
    }
  }

see stackblitz