angularformsangular2-form-validation

how to trigger validation and get validation result after submit form action in Angular?


I have this formgroup:

this.form = this.fb.group({
  id: [],
  active: [true],
  name: [''],
});

and this submit form function:

onSubmit(submitForm: FormGroup) {
  this.submitForm.controls['name'].setValidators([MyValidators.unique(`name`, () => {
     return this.service.checkNameUnique(this.submitForm.value.name, this.labelFg.value.id);
  })]);
}

I didn't set validation to the form when initiating because this form will only be validated after I clicked the submit button. So I use the setValidatorsfunction to set validation in onSubmit function.

But question is: How do I trigger this validation and get the validation result?


Solution

  • Disclamer As andrew say, from Angular 8, it's possible use {updateOn:'submit'} using formBuilder, appologies for the inconvenience.

    You can use the "constructors" of FormGroup and Form controls, not the formBuilder), then you can add {updateOn:'submit'}, see the docs: forms validation

    this.form = new FormGroup({
      id: new FormControl('',Validators.required),
      active: new FormControl(true,Validators.requiredTrue),
      name: new FormControl('',
            {validators:Validators.required,
             asyncValidators:MyValidators),
    },{updateOn:'submit'});
    

    Yes, only can do it using the constructors of FormGroup, but you can see it's not very diferent to use FormBuilder

    Update an stackblitz example