Angular5自定义验证器的反应形式 [英] Angular5 Custom Validators for Reactive forms

查看:55
本文介绍了Angular5自定义验证器的反应形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在为Angular v5应用制作自定义验证器时遇到问题.在文档中仅遵循基本密码匹配示例的文档进行操作,但是该文档无法验证.

I am having problems making a custom validator for my Angular v5 app. Following the docs for just the basic password match example in the Docs but it doesn't validate.

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');

Also, how would I go to be able to use the function with dynamic input names? so that I can use it for emails, etc. Ex: 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>

工作:但是如何传递参数,以便可以将相同的方法用于不同的输入名称.

GOT IT WORKING: but how can I pass parameters so that I can use this same method for different input names.

  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类即可使其进行引导或其他所需的操作.

I think I did what you want. The code is prepared for PrimeNG, but mostly you just have to replace a few css classes to make it ready to bootstrap or other you need.

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

It's a component to validate required fields, minimum length, patterns and custom validations. First, the examples about how to use:

示例1:验证:必填,最小长度和格式.

some.component.html

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

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

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

Example 3: Validate: required, minlength and a custom function envolving 2 fields. 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

some.component.ts

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

如果满足您的需要,代码为:

If it fits your need, the code is:

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

And that's it. I hope it helps. https://gist.github.com/sannonaragao/dbf747676016ed0c4054f8abd2e2a4d2

这篇关于Angular5自定义验证器的反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆