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

时间:2018-01-05 04:38:54

标签: angular

我在为Angular v5应用程序制作自定义验证器时遇到问题。仅关注Docs中基本密码匹配示例的文档,但它不会验证。

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};

}

另外,我如何能够使用动态输入名称的功能? 这样我就可以将它用于电子邮件等 例如:匹配('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>

GOT IT WORKING:但我如何传递参数,以便我可以对不同的输入名称使用相同的方法。

  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 };
  }

1 个答案:

答案 0 :(得分:0)

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

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

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

some.component.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:验证:必需,最小长度和自定义函数。

some.component.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:验证:必需,minlength和包含2个字段的自定义函数。 some.component.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;
}
...

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

<强>输入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