In Angular, how to add Validator to FormControl after control is created?

后端 未结 5 1680
清酒与你
清酒与你 2020-11-30 23:10

We have a component that has a dynamically built form. The code to add a control with validators might look like this:

var c = new FormControl(\'\', Validato         


        
5条回答
  •  有刺的猬
    2020-12-01 00:02

    If you are using reactiveFormModule and have formGroup defined like this:

    public exampleForm = new FormGroup({
            name: new FormControl('Test name', [Validators.required, Validators.minLength(3)]),
            email: new FormControl('test@example.com', [Validators.required, Validators.maxLength(50)]),
            age: new FormControl(45, [Validators.min(18), Validators.max(65)])
    });
    

    than you are able to add a new validator (and keep old ones) to FormControl with this approach:

    this.exampleForm.get('age').setValidators([
            Validators.pattern('^[0-9]*$'),
            this.exampleForm.get('age').validator
    ]);
    this.exampleForm.get('email').setValidators([
            Validators.email,
            this.exampleForm.get('email').validator
    ]);
    

    FormControl.validator returns a compose validator containing all previously defined validators.

提交回复
热议问题