FromGroup

时间:2017-11-11 20:29:42

标签: angular validation typescript angular4-forms

我在第二个FormGroup中使用自定义验证器时的问题。

我验证了我熟悉的FormBuilder,我使用了自定义验证器来验证我的确认密码,但是当我访问密码值时,我遇到了FormGroup的问题。

组件代码:

import {Component, OnInit} from '@angular/core';
import {FormBuilder, Validators, FormGroup} from '@angular/forms';
import {confirmPasswordValidator} from './strong-password.validator';


@Component({
  selector: 'connexion-app',
  templateUrl: './connexion.component.html'
})
export class ConnexionComponentComponent implements OnInit {
  form: FormGroup;


  constructor(protected fb: FormBuilder) {
    this.form = this.fb.group({
      name: this.fb.group({
        firstname: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(25)])],
        lastname: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(25)])]
      }),
      email: ['', Validators.pattern('^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$')],
      verification: this.fb.group({
        password: ['', Validators.compose([Validators.required, Validators.minLength(8)])],
        passwordConfirm: ['', confirmPasswordValidator()]
      })
    });
  }


  ngOnInit(): void {
  }


  save(x: any) {
    console.log(x);
  }

}

import {Component, OnInit} from '@angular/core'; import {FormBuilder, Validators, FormGroup} from '@angular/forms'; import {confirmPasswordValidator} from './strong-password.validator'; @Component({ selector: 'connexion-app', templateUrl: './connexion.component.html' }) export class ConnexionComponentComponent implements OnInit { form: FormGroup; constructor(protected fb: FormBuilder) { this.form = this.fb.group({ name: this.fb.group({ firstname: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(25)])], lastname: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(25)])] }), email: ['', Validators.pattern('^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$')], verification: this.fb.group({ password: ['', Validators.compose([Validators.required, Validators.minLength(8)])], passwordConfirm: ['', confirmPasswordValidator()] }) }); } ngOnInit(): void { } save(x: any) { console.log(x); } }

image

HTML代码:

<form [formGroup]="form" novalidate (ngSubmit)="save(form.value)">
  <div formGroupName="name">
    <input formControlName="firstname" placeholder="firstname">
    <input formControlName="lastname" placeholder="lastname">
  </div>
  <input formControlName="email" placeholder="Email">

  <div formGroupName="verification">
    <input formControlName="password" name="password" placeholder="password">
    <input formControlName="passwordConfirm" name="passwordConfirm" placeholder="passwordConfirm">
  </div>
  <button>Submit</button>
</form>
<p>Value: {{ form.value | json }}</p>
<p>Validation status: {{ form.status }}</p>

image

自定义验证码: <form [formGroup]="form" novalidate (ngSubmit)="save(form.value)"> <div formGroupName="name"> <input formControlName="firstname" placeholder="firstname"> <input formControlName="lastname" placeholder="lastname"> </div> <input formControlName="email" placeholder="Email"> <div formGroupName="verification"> <input formControlName="password" name="password" placeholder="password"> <input formControlName="passwordConfirm" name="passwordConfirm" placeholder="passwordConfirm"> </div> <button>Submit</button> </form> <p>Value: {{ form.value | json }}</p> <p>Validation status: {{ form.status }}</p>

 image

问题:

  

core.es5.js:1020 ERROR错误:未捕获(在承诺中):TypeError:不能   read属性'password'未定义TypeError:无法读取属性   未定义的'密码'       在FormControl.eval [作为验证器](strong-password.validator.ts:6)       在FormControl.AbstractControl._runValidator(forms.es5.js:2720)       在FormControl.AbstractControl.updateValueAndValidity(forms.es5.js:2688)       在新的FormControl(forms.es5.js:3011)       在FormBuilder.control(forms.es5.js:5863)       在FormBuilder._createControl(forms.es5.js:5905)       在eval(forms.es5.js:5887)       在Array.forEach()       在FormBuilder._reduceControls(forms.es5.js:5886)       在FormBuilder.group(forms.es5.js:5845)       在FormControl.eval [作为验证器](strong-password.validator.ts:6)       在FormControl.AbstractControl._runValidator(forms.es5.js:2720)       在FormControl.AbstractControl.updateValueAndValidity(forms.es5.js:2688)       在新的FormControl(forms.es5.js:3011)       在FormBuilder.control(forms.es5.js:5863)       在FormBuilder._createControl(forms.es5.js:5905)       在eval(forms.es5.js:5887)       在Array.forEach()       在FormBuilder._reduceControls(forms.es5.js:5886)       在FormBuilder.group(forms.es5.js:5845)       at resolvePromise(zone.js:824)       at resolvePromise(zone.js:795)       在eval(zone.js:873)       在ZoneDelegate.invokeTask(zone.js:425)       at Object.onInvokeTask(core.es5.js:3881)       在ZoneDelegate.invokeTask(zone.js:424)       在Zone.runTask(zone.js:192)       在drainMicroTaskQueue(zone.js:602)       在defaultErrorLogger @ core.es5.js:1020 ErrorHandler.handleError @ core.es5.js:1080 next @ core.es5.js:4503   schedulerFn @ core.es5.js:3635 SafeSubscriber。 tryOrUnsub @   Subscriber.js:239 SafeSubscriber.next @ Subscriber.js:186   Subscriber._next @ Subscriber.js:127 Subscriber.next @   Subscriber.js:91 Subject.next @ Subject.js:56 EventEmitter.emit @   core.es5.js:3621(匿名)@ core.es5.js:3912 ZoneDelegate.invoke @   zone.js:392 Zone.run @ zone.js:142 NgZone.runOutsideAngular @   core.es5.js:3844 onHandleError @ core.es5.js:3912   ZoneDelegate.handleError @ zone.js:396 Zone.runGuarded @ zone.js:158   _loop_1 @ zone.js:702 api.microtaskDrainDone @ zone.js:711 drainMicroTaskQueue @ zone.js:610 Promise resolved(async)   scheduleMicroTask @ zone.js:585 ZoneDelegate.scheduleTask @   zone.js:414 Zone.scheduleTask @ zone.js:236 Zone.scheduleMicroTask @   zone.js:256 scheduleResolveOrReject @ zone.js:871   ZoneAwarePromise.then @ zone.js:981   PlatformRef _。 bootstrapModuleWithZone @ core.es5.js:4537   PlatformRef .bootstrapModule @ core.es5.js:4522(匿名)@   main.ts:11 ../../../../../src/main.ts @main.bundle.js:207   __webpack_require @ inline.bundle.js:55 0 @main.bundle.js:222    webpack_require @ inline.bundle.js:55 webpackJsonpCallback @ inline.bundle.js:26(匿名)@main.bundle.js:1

image

环境: 角度版本:4.4.6, Angular CLI:1.5, 节点版本:v8.7.0。

1 个答案:

答案 0 :(得分:-1)

最后,我解决了这个问题:

我们需要在Component和Validators中进行相同的更改,如下所示:

验证

import {AbstractControl, ValidatorFn} from '@angular/forms';

export function confirmPasswordValidator(): ValidatorFn {
  return (control: AbstractControl) => {
    return (control.get('password').value === control.get('passwordConfirm').value) ? null : {'strongPasswordError': true};
  };
}

组件:

import {Component, OnInit} from '@angular/core';
import {FormBuilder, Validators, FormGroup, FormControl, AbstractControl} from '@angular/forms';
import {confirmPasswordValidator} from './strong-password.validator';


@Component({
  selector: 'connexion-app',
  templateUrl: './connexion.component.html'
})
export class ConnexionComponentComponent implements OnInit {
  form: FormGroup;


  constructor(protected fb: FormBuilder) {
    this.form = this.fb.group({
      name: this.fb.group({
        firstname: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(25)])],
        lastname: ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(25)])]
      }),
      email: ['', Validators.pattern('^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$')],
      verification: this.fb.group({
        password: ['', Validators.compose([Validators.required, Validators.minLength(8)])],
        passwordConfirm: ['', Validators.compose([Validators.required, Validators.minLength(8)])]
      }, {validator: confirmPasswordValidator()}),
    });
  }

  ngOnInit(): void {
  }


  save(x: any) {
    console.log(x);
  }

}