8

I am wondering how I can add an validator to already created formControl (that was created with it own Validators). But, let's imagine that after some delay I want to add another one (or I have a custom control that contains a few validators itself) and I want to create outer Reactive form and add inner validators to outer.

Is it possible? I didn't found any information (only about re-setting all validators) Thanks for any help!

  this.testForm = this.fb.group({
      testField: [{value: '', disabled: false}, [<any>Validators.required]]
    })

<form [formGroup]="testForm" novalidate>
  <custom_input>
    formControlName="testField"
    [outerFormControl]="testForm.controls.testField"
    </custom_input>


</form>

and after that I want to add other validator inside my custom controls. How I can do that?

custom_coontrol.ts

this.outerFormControl.push(Validators.maxLength(10));

1 Answer 1

13
@Component({
  selector: 'my-app',
  template: `
   <form [formGroup]="testForm" novalidate>
    <input type="text" formControlName="age">
   </form>
   <button (click)="addValidation()">Add validation</button>

   {{ testForm.valid | json }}
  `,
})
export class App {

  constructor(private fb: FormBuilder) {
     this.testForm = this.fb.group({
      age: [null, Validators.required]
    })
  }

  addValidation() {
    this.testForm.get('age').setValidators(Validators.maxLength(2));
  }
}

Plunker

Sign up to request clarification or add additional context in comments.

5 Comments

Cool. It works. Thank you Patrick! But how it possible? I read that using SetValidators will override previous validatords. NG2 API: Sets the synchronous validators that are active on this control. Calling this will overwrite any existing sync validators.
I guess they changed that or something
Okay, I checked the source code and this method will add new validators to exist validators in case when passed validators will be in array. In other case it will override previous validators. Here is the source: function coerceToValidator(validator: ValidatorFn | ValidatorFn[]): ValidatorFn { return Array.isArray(validator) ? composeValidators(validator) : validator; }
In case this helps someone else: This alone doesn't work in Angular 6. I needed to add this.testForm.get('age').updateValueAndValidity({onlySelf: true, emitEvent: false}); after setting the validators.
If it's needed to assign a validation function dynamically (not only while form control initialization), built-in Angular Form method setValidators() is good idea to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.