Angular 5多重输入验证

时间:2018-10-30 21:15:03

标签: javascript angular forms

我试图进行自定义验证,所以我创建了以下指令:

import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, Validator} from '@angular/forms';
@Directive({
    selector: '[appEqualValidator]',
    providers: [
        {provide: NG_VALIDATORS, useExisting: EqualValidatorDirective, multi: true}
    ]
})
export class EqualValidatorDirective implements Validator {
    @Input('inputOne')
    inputOne: string;
    @Input('inputTwo')
    inputTwo: string;

    constructor() {
    }

    validate(c: AbstractControl) {

        const value = c.value;
        if ((value == null || value === undefined || value === '') && this.inputOne === this.inputTwo) {
            return {
                equalTo: {condition: this.inputOne === this.inputTwo}
            };
        }
        return null;
    }
}

现在我正在尝试将其添加到表单中,但是使用多个输入存在一些问题:

 <div class="form-group">
    <label>E-mail</label>
    <input type="email" class="form-control" placeholder="Indtast email" [(ngModel)]="model.email" name="email" [email]="true" required/>
</div>
<div class="form-group">
    <label style="display: block">Gentag E-mail</label>
    <input type="email" class="form-control" placeholder="Gentag email" [(ngModel)]="model.emailRepeat" required [email]="true" 
[appEqualValidator]="value" name="emailRepeat"/>
    <li *ngIf="!emailVerify">
        De to emails er ikke ens
    </li>
</div>

我不确定如何在表格中使用指令。并确保我可以同时获得两个输入。

我希望你们中的一些人能指出正确的方向。

2 个答案:

答案 0 :(得分:2)

我对反应形式做了类似的事情。

这里是验证者:

function emailMatcher(c: AbstractControl): { [key: string]: boolean } | null {
  const emailControl = c.get('email');
  const confirmControl = c.get('confirmEmail');

  if (emailControl.pristine || confirmControl.pristine) {
    return null;
  }

  if (emailControl.value === confirmControl.value) {
    return null;
  }
  return { 'match': true };
}

这是表单生成器:

this.customerForm = this.fb.group({
  firstName: ['', [Validators.required, Validators.minLength(3)]],
  lastName: ['', [Validators.required, Validators.maxLength(50)]],
  emailGroup: this.fb.group({
    email: ['', [Validators.required, Validators.email]],
    confirmEmail: ['', Validators.required],
  }, { validator: emailMatcher }),
  phone: ''
});

这是HTML:

<div class="form-group row">
  <label class="col-md-2 col-form-label"
         for="emailId">Email</label>
  <div class="col-md-8">
    <input class="form-control"
           id="emailId"
           type="email"
           placeholder="Email (required)"
           formControlName="email"
           [ngClass]="{'is-invalid': customerForm.get('emailGroup').errors ||
                                      ((customerForm.get('emailGroup.email').touched || 
                                      customerForm.get('emailGroup.email').dirty) && 
                                      !customerForm.get('emailGroup.email').valid) }" />
    <span class="invalid-feedback">
      <span *ngIf="customerForm.get('emailGroup.email').errors?.required">
        Please enter your email address.
      </span>
      <span *ngIf="customerForm.get('emailGroup.email').errors?.email">
        Please enter a valid email address.
      </span>
    </span>
  </div>
</div>

<div class="form-group row">
  <label class="col-md-2 col-form-label"
         for="confirmEmailId">Confirm Email</label>
  <div class="col-md-8">
    <input class="form-control"
           id="confirmEmailId"
           type="email"
           placeholder="Confirm Email (required)"
           formControlName="confirmEmail"
           [ngClass]="{'is-invalid': customerForm.get('emailGroup').errors ||
                                     ((customerForm.get('emailGroup.confirmEmail').touched || 
                                      customerForm.get('emailGroup.confirmEmail').dirty) && 
                                      !customerForm.get('emailGroup.confirmEmail').valid) }" />
    <span class="invalid-feedback">
      <span *ngIf="customerForm.get('emailGroup.confirmEmail').errors?.required">
        Please confirm your email address.
      </span>
      <span *ngIf="customerForm.get('emailGroup').errors?.match">
        The confirmation does not match the email address.
      </span>
    </span>
  </div>
</div>

您可以在此处找到完整的解决方案:

https://github.com/DeborahK/Angular-ReactiveForms/tree/master/Demo-Final-Updated/src/app/customers

答案 1 :(得分:1)

您可以将两个输入都包装在NgModelGroup中。它扩展了AbstractControlDirective,因此可能需要验证器。

<div ngModelGroup="emails" #emails="ngModelGroup" [appEqualValidator]="value">
    <div class="form-group">
        <label>E-mail</label>
        <input type="email" class="form-control" placeholder="Indtast email" [(ngModel)]="model.email" name="email" [email]="true" required/>
    </div>
    <div class="form-group">
        <label style="display: block">Gentag E-mail</label>
        <input type="email" class="form-control" placeholder="Gentag email" [(ngModel)]="model.emailRepeat" required [email]="true" name="emailRepeat"/>
        <li *ngIf="!emailVerify">De to emails er ikke ens</li>
    </div>
</div>

每当子控件更改时,都会调用组验证器。在validate()中,您将需要强制转换为FormGroup并输入值相等。

Read More Here