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

感情迁移 提交于 2020-01-25 06:47:08

问题


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:


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

You can usethe "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




回答2:


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:


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



来源:https://stackoverflow.com/questions/58387436/how-to-trigger-validation-and-get-validation-result-after-submit-form-action-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!