1

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?

1

3 Answers 3

4

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

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

1 Comment

When I used update on the field is marked with errors, however in order to get the field to go back I have to click submit again. Does the form no longer have realtime error checking with the updateOn feature?
2

Try this

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

angular-setvalidators

Update Check out this blog to get the best example about angular async-validators

4 Comments

I used setAsyncValidators instead. I need to save the form value to database if the form validation result is true. But I just can't get that result
When you add or remove a (setValidators/setAsyncValidators) validator at run time, you must call updateValueAndValidity() for the new validation to take effect. setasyncvalidators
It worked! But how do I use this.submitForm.get('name').status? the setAsyncValidators is async. I need the validation result right after that
@Liem - check the updated answer. I hope, 'validateEmailNotTaken' method will help you to achieve what you are trying.
1

There's nothing stopping you using FormBuilder API and passing AbstractControlOptions. You can pass these options to the controls and/or the group.

this.formGroup = this.fb.group({
  id: ['', [Validators.required]],
  name: ['', {validators: ..., asyncValidators: ..., updateOn: ...}],
}, { updateOn: 'submit' });

Stackblitz

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators} from '@angular/forms'

@Component({
  selector: 'my-app',
  template: `
  <form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
      <input type="text" placeholder="Id" formControlName="id" />
      <input type="text" placeholder="Name" formControlName="name" />

      <br/>
      <br/>
    <h3>Value</h3>
      {{ formGroup.value | json }}
    <h3>Valid</h3>
      {{ formGroup.valid | json }}

      <br/>
      <br/>
    <button type="submit" >Submit</button>

  </form>
  `
})
export class AppComponent  {
  formGroup: FormGroup

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.formGroup = this.fb.group({
      id: ['', [Validators.required]],
      name: [''],
    }, { updateOn: 'submit' });
  }

  onSubmit() {
    console.log('onSubmit')
    console.log(this.formGroup.value)
    console.log(this.formGroup.valid)
  }
}

3 Comments

good point :). you can use {updateOn:'blur'} with FormBuilder too from Angular 8
questions is: before click submit button or before validation, the form.valid is always false.
form.valid is always false because until it updates it has value { id: "", name: "" }. I would say this is intended behaviour

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.