用于反应式表单的 Angular5 自定义验证器



我在为 Angular v5 应用程序创建自定义验证器时遇到问题。仅按照文档中的基本密码匹配示例进行操作,但不会进行验证。

this.personalInfoForm = _fb.group({
  'name': [null,Validators.minLength(7)],
  'email': [null, CustomValidators.emailOrEmpty],
  'password':[null],
  'password_confirm': [null]
}, this.passwordMatch); 

//EDIT
passwordMatch(g: FormGroup) {
      return g.get('password').value === g.get('password_confirm').value ?  null : {'mismatch': true};
}

另外,我将如何能够将函数与动态输入名称一起使用?这样我就可以将其用于电子邮件等。例如:match('inputToMatch'(;

编辑:添加了HTML

<form class="col-lg-12" [formGroup]="personalInfoForm" (ngSubmit)="updatePersonalSettings(personalInfoForm.value)">
<h4>Basic Information</h4>
<div class="form-group row ">
  <label for="name" class="col-sm-2 col-form-label">Full Name</label>
  <div class="col-sm-6">
    <input 
      type="text" 
      class="form-control" 
      id="name" 
      placeholder="{{currentUser.name}}" 
      formControlName="name"
      />
  </div>
</div>
<div class="form-group row">
  <label for="email" class="col-sm-2 col-form-label">Email Address</label>
  <div class="col-sm-6">
    <input 
      type="email" 
      class="form-control" 
      id="email" 
      placeholder="{{currentUser.email}}" 
      formControlName="email"
      value=" ">
  </div>
</div>
<h4>Password</h4>
<div class="form-group row">
  <label for="password" class="col-sm-2 col-form-label">Password</label>
  <div class="col-sm-6">
    <input 
      type="password" 
      class="form-control" 
      id="password" 
      formControlName="password"
      placeholder="password">
  </div>
</div>
<div class="form-group row">
  <label for="password_confirm" class="col-sm-2 col-form-label">Confirm Password</label>
  <div class="col-sm-6">
    <input 
      type="email" 
      class="form-control" 
      id="password_confirm"
      formControlName="password_confirm" 
      placeholder="password confirmation" >
  </div>
</div>
<br>
<button [disabled]="!personalInfoForm.valid || !personalInfoForm.dirty" type="submit" class="btn btn-primary">Save</button>

让它工作: 但是我如何传递参数,以便我可以对不同的输入名称使用相同的方法。

  passwordMatch(control: AbstractControl) {
    const password = control.root.get('password');
    const confirm = control.value;
  if (!password || !confirm) return null;
    return password.value === confirm ? null : { nomatch: true };
  }

我想我做了你想做的。 该代码是为PrimeNG准备的,但大多数情况下,您只需要替换一些css类即可使其准备好引导程序或其他您需要的类。

它是验证必填字段、最小长度、模式和自定义验证的组件。首先,关于如何使用的示例:

示例 1:验证:必需、最小长度和模式。

一些组件.html

<input pInputText type="text" name="email"  [(ngModel)]="user.email"
    ngModel #email="ngModel" required minlength="5"
    pattern="^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$">
<app-input-validation [control]="email"
    [errDef]="{ required: 'A email is required',
    pattern:  'Enter a valid email address',
    minlength: 'The email should be at least 5 characteres'}" >
</app-input-validation>

示例 2:验证:必需、最小长度和自定义函数。

一些组件.html

<input pInputText type="text" name="name"  [(ngModel)]="user.name" 
    ngModel #name="ngModel" required minlength="5">
<app-input-validation [control]="name" [custom]="validateField1"
    [errDef]="{ required:  'A name is required',
    custom:    'Name must be diferent from sysadm',
    minlength: 'The name should be at least 5 characteres'}" >
</app-input-validation>

some.component.ts

...
// This validation funcion is called by the parâmeter [custom]="validateField1"
// and the component receive the field as argument. 
validateField1(context: NgModel ): boolean {
    if ( context.control.value === 'sysadm') {
        return false;
    }
    return true;
...

示例 3:验证:必填、最小长度和包含 2 个字段的自定义函数。一些组件.html

...
<form #f="ngForm" autocomplete="off" (ngSubmit)="save(f)">
...
<div class="ui-md-6 ui-g-12 ui-fluid">
   <label>Password</label>
   <input pPassword type="password"  name="password"  
       [(ngModel)]="user.password" 
       ngModel #password="ngModel" required minlength="5" >
</div>
<div class="ui-md-6 ui-g-12 ui-fluid">
    <label>Retype Password</label>
    <input pPassword type="password"  name="repassword"
          [(ngModel)]="user.repassword" required minlength="5"  >
</div>
<!-- the parameter [form]="f" must be passed to app-input-validation 
    because the validatePassword must use 2 fields from the form -->
....
<app-input-validation [control]="password" [custom]="validatePassword"
    [form]="f" 
    [errDef]=
        "{  required: 'A password is required',
            custom:    'Both passwords must match.',
            minlength: 'The email should be at least 5 characteres'}" >
</app-input-validation>
</div>

some.component.ts

...
validatePassword(context: NgForm ): boolean {
if ( context.form.value.password === context.form.value.repassword ) {
    return true;
}
return false;
}
...

如果符合您的需要,代码为:

input-validation.component.ts

import { FormControl } from '@angular/forms';
import { Component, OnInit, Input } from '@angular/core';
import { NgModel, NgForm } from '@angular/forms';
@Component({
selector: 'app-input-validation',
template: `
<div *ngIf="hasError()" class="ui-message ui-messages-error">
  {{ errorMessage }}
</div>
`,
styles: [`
.ui-messages-error {
  margin: 0;
  margin-top: 4px;
}
`]
})
export class InputValidationComponent {
@Input() control: NgModel;
@Input() form: NgForm;
@Input() errDef: any;
@Input() custom: any;
errorMessages = [];
errorMessage = '';
hasError(): boolean {
this.errorMessages = [];
this.errorMessage = '';
if ( this.errDef && ( this.control.errors || this.errDef['custom'] ) ) {
  Object.keys(this.errDef).some(key => {
    if ( this.control.errors && this.control.errors[key]) {
      this.errorMessages.push(this.errDef[key]);
    } else if ( key === 'custom' && !this.runCustom() ) {
      this.errorMessages.push(this.errDef[key]);
    }
    return false;
  });
}
for ( const m of this.errorMessages ){
  if ( this.errorMessage.length > 0 ) {
    this.errorMessage = this.errorMessage + '.  ';
  }
  this.errorMessage = this.errorMessage + m;
}
return this.errorMessages.length > 0  && this.control.dirty;
}
public runCustom(): boolean {
return this.custom(this);
}
}

仅此而已。 我希望它有所帮助。https://gist.github.com/sannonaragao/dbf747676016ed0c4054f8abd2e2a4d2

最新更新