将验证器中的字段与angular2进行比较

时间:2015-11-17 22:55:05

标签: typescript angular

我正在尝试在Angular2中创建一个注册表单,其中包含一个"重复密码"功能。我希望这可以使用自定义验证器作为表单控件。

我遇到的问题是"这个背景"似乎在验证程序运行时设置为验证程序,因此我无法访问RegistrationForm类上的任何本地方法。我似乎无法找到从验证器访问ControlGroup的任何好方法。

任何人都知道在自定义验证器中访问同一控件组中的其他控件的好方法吗?

该组件的简短示例:

import { Component, View } from 'angular2/angular2';
import { Validators, ControlGroup, Control, FORM_DIRECTIVES, FORM_BINDINGS } from 'angular2/angular2';

@Component({
    selector: 'form-registration'
})
@View({
    directives: [FORM_DIRECTIVES, ROUTER_DIRECTIVES],
    template: `
        <form (submit)="register($event)" [ng-form-model]="registerForm">
            <label for="password1">Password:</label>
            <input id="password1" ng-control="password1" type="password" placeholder="Passord" />

            <label for="password2">Repeat password:</label>
            <input id="password2" ng-control="password2" type="password" placeholder="Gjenta passord" />

            <button class="knapp-submit" type="submit" [disabled]="!registerForm.valid">Registrer deg</button>
        </form>
    `
})
export class RegistrationForm {
    registerForm: ControlGroup;

    constructor() {            
        this.registerForm = new ControlGroup({
            password1: new Control('', Validators.required),
            password2: new Control('', this.customValidator)
        });
    }

    public register(event: Event) {
        // submit form
    }

    private customValidator(control: Control) {
        // check if control is equal to the password1 control
        return {isEqual: control.value === this.registerForm.controls['password1'].value};
    }
}

2 个答案:

答案 0 :(得分:5)

所以我通过将customValidator绑定到我的类的this-context来解决问题,如Sergio的评论所述。

请记住.bind(this)函数返回带有bound-context的函数的新实例。

import { Component, View } from 'angular2/angular2';
import { Validators, ControlGroup, Control, FORM_DIRECTIVES, FORM_BINDINGS } from 'angular2/angular2';

@Component({
    selector: 'form-registration'
})
@View({
    directives: [FORM_DIRECTIVES, ROUTER_DIRECTIVES],
    template: `...my form template...`
})
export class RegistrationForm {
    registerForm: ControlGroup;

    constructor() {           
        this.customValidator = this.customValidator.bind(this); 
        this.registerForm = new ControlGroup({
            password1: new Control('', Validators.required),
            password2: new Control('', this.customValidator)
        });
    }

    public register(event: Event) {
        // submit form
    }

    private customValidator(control: Control) {
        // check if control is equal to the password1 control
        return {isEqual: control.value === this.registerForm.controls['password1'].value};
    }
}

答案 1 :(得分:-3)

尝试使用此代码进行验证。它成功运作!!!!

Register.component.html

<div class="signin-content">
    <mat-card>
      <mat-card-content>
        <form [formGroup]="userForm1" (ngSubmit)="onSubmit()">
          <p>Please Register Here</p>
          <mat-input-container class="full-width-input">
            <input matInput placeholder=" First Name" formControlName="firstname" >
          </mat-input-container>
          <mat-input-container class="full-width-input">
            <input matInput  placeholder="Last Name"   formControlName="lastname" >
          </mat-input-container>
          <mat-input-container class="full-width-input">
            <input matInput placeholder="Phone No."   formControlName="phone" required>
            <div *ngIf="userForm1.controls['phone'].hasError('pattern')" class="alert alert-danger" >
                please Enter 10 digits....
            </div>
          </mat-input-container>
          <mat-input-container class="full-width-input">
            <input matInput  placeholder="E-mail"   formControlName="email"  required>
            <span *ngIf="userForm1.hasError('email', 'email') && userForm1.get('email').touched" class="alert-danger">
                Please enter valid email contains '@','.' ...
              </span>
          </mat-input-container>
          <mat-input-container class="full-width-input">
            <input matInput type="password" placeholder="Password"   formControlName="password" required >
          </mat-input-container>
          <mat-input-container class="full-width-input">
            <input matInput type="password" placeholder="Confirm Password"   formControlName="cpassword" required>
            <div  *ngIf="userForm1.controls['cpassword'].errors?.MatchPassword && userForm1.get('cpassword').touched " class="alert alert-danger">
                Password not match
            </div>
          </mat-input-container>
          <button mat-raised-button [disabled]="!userForm1.valid" color="primary" type="submit">Register</button>

        </form>
      </mat-card-content>
    </mat-card>
  </div>

Register.component.ts

import { Component, OnInit, Output, EventEmitter, ViewChild } from '@angular/core';

import { MatGridListModule, MatButtonModule, MatInputModule, MatDialog,MatDialogRef } from '@angular/material';

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

import {HttpClient} from '@angular/common/http';

import { Router } from '@angular/router'

import 'rxjs/add/operator/map';

import { Headers, Http, RequestOptions } from '@angular/http';

import { EqualTextValidator } from "angular2-text-equality-validator";

import { PasswordValidation } from './Passwordvalidation';

@Component({

  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']

})

export class RegistrationComponent implements OnInit {

  userForm1:FormGroup;
  password = 'password';

  constructor( private _formBuilder: FormBuilder,
    // public thisDialogref: MatDialogRef<AppComponent>  ,
    private http:HttpClient,
    private router: Router){}

  ngOnInit() {

    this.userForm1=this._formBuilder.group({

      id:[""],
      firstname:[""],
      lastname: [""],
      phone:[null,[Validators.required, Validators.pattern('^[1-9][0-9]{9}$'),Validators.maxLength(10)]],

      email:[null,[Validators.required,Validators.email]],
      password:["",[Validators.compose([Validators.required])]],
      cpassword:["",[Validators.required]],
      createdDate:[""],
      updatedDate:[""],
      status:[""]
    },{
      validator: PasswordValidation.MatchPassword // your validation method
    })
  }

  onSubmit(){
    console.log(this.userForm1.value);
    this.http.post("http://localhost:4001/user/signup",this.userForm1.value).subscribe(result => {
      console.log("register successful");
     });
     this.router.navigate(['/login']);
  }

}

Passwordvalidation.ts

从&#39; @ angular / forms&#39;中导入{AbstractControl}; export class PasswordValidation {

static MatchPassword(AC: AbstractControl) {
   let password = AC.get('password').value; // to get value in input tag
   let cpassword = AC.get('cpassword').value; // to get value in input tag
    if(password != cpassword) {
        console.log('false');
        AC.get('cpassword').setErrors( {MatchPassword: true} )
    } else {
        console.log('true');
        return null
    }
}

}