简体   繁体   English

如何验证反应形式(模型驱动形式)控制值是否与angular2中的现有值重复?

[英]How to validate a reactive form(Model Driven Form) control value whether it is duplication of an existing value in angular2?

I have a list of team names which I'm getting from a service. 我有从服务中获得的团队名称列表。 While creating a new team using reactive form, I want to add a custom validator to teamName text box to check whether that name is already existing or not. 在使用反应形式创建新团队时,我想向teamName文本框添加一个自定义验证器,以检查该名称是否已经存在。 Can any one please let me know how to do it? 有人可以让我知道怎么做吗? Is this possible to add a validator in this case? 在这种情况下是否可以添加验证器?

Here is a simple example of how it can be done. 这是一个简单的例子。 Below is the app.component.ts 以下是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

Your validator goes in as your second argument in the Form Control and insert your array of names as your validators argument. 验证器将作为表单控件中的第二个参数进入,并插入名称数组作为验证器参数。 Assuming you have your list of names in an array. 假设您的名称列表在一个数组中。 Below is the custom-validators.ts 以下是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

your validator will go through each element of the arrayOfNames (as well as lowercasing and removing whitespace from either ends to accurately compare) and seeing if it is equal to the value in the control. 您的验证器将遍历arrayOfNames的每个元素(以及从两端精简和删除空格以进行精确比较),并查看其是否等于控件中的值。 If none has matched it will return null (meaning no errors) otherwise reporting one has matched (which will return an error). 如果没有一个匹配,它将返回null(表示没有错误),否则报告一个已匹配(将返回一个错误)。 Make sure you do all necessary import in the component and module. 确保在组件和模块中进行了所有必要的导入。 Hope it helps! 希望能帮助到你! Below is the app.module just in case. 以下是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 { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何格式化 Angular Reactive Form Control 值 - How to format an Angular Reactive Form Control value 如何编写依赖于Angular2中当前组件的属性值的自定义表单验证器(模型驱动) - How to write custom form validator (model-driven) that depends on current component's property value in Angular2 Angular2反应形式默认输入值 - Angular2 reactive form default input value “ [值]”未以反应形式设置控制值 - '[value]' not setting control value in reactive form Angular 如何在Angular6中为Reactive Form控件设置值? - How to set value to a Reactive Form control in Angular6? 如何检查反应形式中的任何控件在 Angular 2 中是否具有价值 - How to check if any control in a reactive form has value in Angular 2 如何在角度反应形式控件中添加小数,其值从 1 和更大开始 - how to add decimal in angular reactive form control with value starting with 1 and greater 如何以 Angular 反应形式正确设置自定义单选按钮控件的值? - How to properly set the value of a custom radiobutton control in an Angular reactive form? 如何在 Angular 的反应式表单中设置表单控件的值 - How to set value to form control in Reactive Forms in Angular Angular2模型驱动的动态表单验证 - Angular2 Model Driven Dynamic Form Validation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM