【问题标题】:Angular 5 multiple input validationAngular 5 多输入验证
【发布时间】:2018-10-30 21:15:03
【问题描述】:

我正在尝试进行自定义验证,因此我创建了以下指令:

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>

我不确定如何在表单中使用指令。并确保我可以得到两个输入。

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

【问题讨论】:

  • 你考虑过使用响应式表单吗? Angular 有验证器,你可以毫不费力地实现这些验证器。见这里:angular.io/guide/form-validation
  • @IvanS95 这是否有一个等于你可以匹配两个输入字段的地方?

标签: javascript angular forms


【解决方案1】:

我对响应式表单做了类似的事情。

这里是验证器:

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

【讨论】:

    【解决方案2】:

    您可以在 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

    【讨论】:

    • 嘿,伙计,当我尝试这个时,我得到:无法绑定到“appEqualValidator”,因为它不是“div”的已知属性
    猜你喜欢
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多