【问题标题】:How to validate a reactive form(Model Driven Form) control value whether it is duplication of an existing value in angular2?如何验证反应形式(模型驱动形式)控制值是否与angular2中的现有值重复?
【发布时间】:2017-09-06 09:08:27
【问题描述】:

我有一个从服务中获得的团队名称列表。在使用响应式表单创建新团队时,我想向 teamName 文本框添加一个自定义验证器,以检查该名称是否已经存在。任何人都可以让我知道该怎么做吗?在这种情况下是否可以添加验证器?

【问题讨论】:

  • 我有类似的问题
  • 有人可以帮忙吗?

标签: angular angular2-forms angular2-services angular2-directives


【解决方案1】:

这里有一个简单的例子来说明如何做到这一点。下面是app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { CustomValidator } from './custom-validators';

const prevNames = ['hector', 'steve', 'adam', 'peter'];

@Component({
  selector: 'app-root',
  template: `
   <div [formGroup]="newName">
     <input formControlName="newName">
   </div>`,
  styleUrls: [`./app.component.css`]
  })
export class AppComponent implements OnInit {
  newName: FormGroup;
  constructor(private fb: FormBuilder) { }
  ngOnInit() {
    this.newName = this.fb.group({
      newName: this.fb.control('',CustomValidator.checkNamesMatched(prevNames))
    });
  } // End Of Init
} // End of Class

您的验证器作为表单控件中的第二个参数进入,并将您的名称数组作为验证器参数插入。 假设您有一个数组中的名称列表。下面是custom-validators.ts

export class CustomValidator {
static checkNamesMatched(arrayOfNames: string[]) {
    return (control) => {
        let matched = false;
        arrayOfNames.forEach((value) => {
            if (value.toLowerCase().trim() === control.value.toLowerCase().trim()) {
                return matched = true;
            }
        });
        return (!matched) ? null : { checkNamesMatched: true };
    };
  } // End of method
} // End of Class

您的验证器将遍历 arrayOfNames 的每个元素(以及从两端小写和删除空格以进行准确比较)并查看它是否等于控件中的值。如果没有匹配,它将返回 null(意味着没有错误),否则报告一个匹配(这将返回错误)。确保在组件和模块中执行所有必要的导入。希望能帮助到你!下面是 app.module 以防万一。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

【讨论】:

    猜你喜欢
    • 2016-11-16
    • 2017-11-22
    • 2017-11-02
    • 2018-05-27
    • 2017-04-14
    • 2016-10-19
    • 1970-01-01
    • 2017-08-05
    • 2018-02-03
    相关资源
    最近更新 更多