如何为角形反应形式的形式值添加自定义唯一验证器?

如何解决如何为角形反应形式的形式值添加自定义唯一验证器?

我想添加一个自定义的唯一验证器,它将验证所有标签字段的值都是唯一的。 (I)当我更改表单值时,this.form的值会在 CustomValidator.uniqueValidator(this.form)中传递后更改。如何解决这个问题? (II)有没有不用任何包装的方法吗?

注意:表单在加载时具有默认值。这是屏幕截图。

enter image description here

this.form = this.fb.group({
      fields: this.fb.array([])
    });

private addFields(fieldControl?) {
return this.fb.group({
  label: [
    {value: fieldControl ? fieldControl.label : '',disabled: this.makeComponentReadOnly},[
    Validators.maxLength(30),CustomValidator.uniqueValidator(this.form)
    ]],isRequired: [
    {value: fieldControl ? fieldControl.isRequired : false,disabled: this.makeComponentReadOnly}],type: [fieldControl ? fieldControl.type : 'text']
});

}

  static uniqueValidator(form: any): ValidatorFn | null {
return (control: AbstractControl): ValidationErrors | null => {
  console.log('control..: ',control);
  const name = control.value;

  if (form.value.fields.filter(v => v.label.toLowerCase() === control.value.toLowerCase()).length > 1) {
    return {
      notUnique: control.value
    };
  } else {
    return null;
  }

}; }

解决方法

在现实生活中,用户名或电子邮件属性被检查为唯一。这将是一个很长的答案,希望您能继续。我将展示如何检查用户名的唯一性。

要检查数据库,您必须创建一个服务以发出请求。因此此验证器将为异步验证器,并将其编写为类。此类将通过依赖项注入技术与服务进行通信。

首先需要设置HttpClientModule。在app.module.ts

import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [AppComponent],imports: [BrowserModule,YourOthersModule,HttpClientModule],providers: [],bootstrap: [AppComponent],})

然后创建服务

 ng g service Auth //named it Auth

在此auth.service.ts中

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',})
export class AuthService {
  constructor(private http: HttpClient) {}
  userNameAvailable(username: string) {
 // avoid type "any". check the response obj and put a clear type
    return this.http.post<any>('https://api.angular.com/username',{
      username:username,});
  }
}

现在创建一个类ng g class UniqueUsername并在该类中:

import { Injectable } from '@angular/core';
import { AsyncValidator,FormControl } from '@angular/forms';
import { map,catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { AuthService } from './auth.service';
// this class needs to use the dependency injection to reach the http client to make an api request
// we can only access to http client with dependecny injection system
// now we need to decorate this class with Injectable to access to AuthService
@Injectable({
  providedIn: 'root',})
export class UniqueUsername implements AsyncValidator {
  constructor(private authService: AuthService) {}
  //this will be used by the usernamae FormControl
  //we use arrow function cause this function will be called by a 
  different context,but we want it to have this class' context 
  because this method needs to reach `this.authService`. in other 
  context `this.authService` will be undefined.
  // if this validator would be used by the FormGroup,you could use 
  "FormGroup" type.
  //if you are not sure you can  use type "control: AbstractControl"
  //In this case you use it for a FormControl
  
    validate = (control: FormControl) => {
    const { value } = control;
    return this.authService.userNameAvailable(value).pipe(
    //errors skip the map(). if we return null,means we got 200 response 
    code,our request will indicate that username is available
    //catchError will catch the error
      map(() => {
        return null;
      }),catchError((err) => {
        console.log(err);
     //you have to console the error to see what the error object is. so u can 
     set up your logic based on properties of the error object.
   // i set as err.error.username as an  example. your api server might 
    return an error object with different properties.
        if (err.error.username) {
   //catchError has to return a new Observable and "of" is a shortcut
   //if err.error.username exists,i will attach `{ nonUniqueUsername: true }`
   to the formControl's error object.
           return of({ nonUniqueUsername: true });
        }
        return of({ noConnection: true });
      })
    );
  };
}

到目前为止,我们已经处理了服务和异步类验证器,现在我们在表单上实现了它。我将只有用户名字段。

import { Component,OnInit } from '@angular/core';
import { FormGroup,FormControl,Validators } from '@angular/forms';
import { UniqueUsername } from '../validators/unique-username';

@Component({
  selector: 'app-signup',templateUrl: './signup.component.html',styleUrls: ['./signup.component.css'],})
export class SignupComponent implements OnInit {
  authForm = new FormGroup(
    {
      // async validators are the third arg
      username: new FormControl(
        '',[
          Validators.required,Validators.minLength(3),Validators.maxLength(20),Validators.pattern(/^[a-z0-9]+$/),],// async validators are gonna run after all sync validators 
     successfully completed running because async operations are 
     expensive.
        this.uniqueUsername.validate
      ),},{ validators: [this.matchPassword.validate] }
  );
  constructor(
    private uniqueUsername: UniqueUsername
  ) {}


//this is used inside the template file. you will see down below
showErrors() {
    const { dirty,touched,errors } = this.control;
    return dirty && touched && errors;
  }
  ngOnInit(): void {}
}

最后一步是向用户显示错误:在表单组件的模板文件中:

<div class="field">
  <input  formControl="username"  />
  <!-- this is where you show the error to the client -->
  <!-- showErrors() is a method inside the class -->
  
  <div *ngIf="showErrors()" class="ui pointing red basic label">
    <!-- authForm.get('username') you access to the "username" formControl -->
    <p *ngIf="authForm.get('username').errors.required">Value is required</p>
    <p *ngIf="authForm.get('username').errors.minlength">
      Value must be longer
      {{ authForm.get('username').errors.minlength.actualLength }} characters
    </p>
    <p *ngIf="authForm.get('username').errors.maxlength">
      Value must be less than {{ authForm.get('username').errors.maxlength.requiredLength }}
    </p>
    <p *ngIf="authForm.get('username').errors.nonUniqueUsername">Username is taken</p>
    <p *ngIf="authForm.get('username').errors.noConnection">Can't tell if username is taken</p>
  </div>
</div>
,

您可以在父元素(ngModelGroup 或表单本身)上创建一个验证器指令:

import { Directive } from '@angular/core';
import { FormGroup,ValidationErrors,Validator,NG_VALIDATORS } from '@angular/forms';

@Directive({
  selector: '[validate-uniqueness]',providers: [{ provide: NG_VALIDATORS,useExisting: UniquenessValidator,multi: true }]
})
export class UniquenessValidator implements Validator {

  validate(formGroup: FormGroup): ValidationErrors | null {
    let firstControl = formGroup.controls['first']
    let secondControl = formgroup.controls['second']
    // If you need to reach outside current group use this syntax:
    let thirdControl =  (<FormGroup>formGroup.root).controls['third']

    // Then validate whatever you want to validate
    // To check if they are present and unique:
    if ((firstControl && firstControl.value) &&
        (secondControl && secondControl.value) &&
        (thirdContreol && thirdControl.value) &&
        (firstControl.value != secondControl.value) &&
        (secondControl.value != thirdControl.value) &&
        (thirdControl.value != firstControl.value)) {
      return null;
    }

    return { validateUniqueness: false }
  }

}

您可能可以简化该检查,但我认为您明白这一点。 我没有测试这段代码,但如果你想看一看,我最近对这个项目中的 2 个字段做了类似的事情:

https://github.com/H3AR7B3A7/EarlyAngularProjects/blob/master/modelForms/src/app/advanced-form/validate-about-or-image.directive.ts

不用说,像这样的自定义验证器是相当特定于业务的,并且在大多数情况下难以重复使用。更改表单可能需要更改指令。还有其他方法可以做到这一点,但这确实有效,而且是一个相当简单的选择。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-