【问题标题】:Validator directive for reactive forms in AngularAngular 中反应式表单的验证器指令
【发布时间】:2020-09-19 14:09:22
【问题描述】:

从这里:https://stackoverflow.com/a/42999816/462608

这是我尝试过的:

whitespace-validator.directive.ts

import { Directive } from '@angular/core';
import { AbstractControl, FormControl, ValidationErrors } from '@angular/forms';

@Directive({
  selector: '[appWhitespaceValidator]'
})

export class WhitespaceValidatorDirective 
{
  constructor() {}

  static appWhitespaceValidator( control: FormControl ): ValidationErrors 
  {
    const isWhitespace = (control.value || '').trim().length === 0;
    const isValid      = !isWhitespace;

    return isValid ? null : { 'whitespace': true };
  }
}

xyz.ts

import { WhitespaceValidatorDirective } from '../whitespace-validator.directive'

...

 this.objFormGroup = this.objFormBuilder.group(
      {
        blogTitle: [ this.blogs[this.mBlogId].title, [Validators.required, Validators.minLength(5)  ] ],
        body:      [ this.blogs[this.mBlogId].body ],
        category:  [ this.blogs[this.mBlogId].category ]
      } )

  get getBlogTitle()
  {
    return this.objFormGroup.get('blogTitle') as FormControl;
  }

xyz.html

<div *ngIf = "getBlogTitle.errors?.appWhitespaceValidator">
  No spaces are allowed.
</div>

请说明使用此验证器指令的正确方法。这里没有错误,但表单仍然没有抱怨 w.r.t 空格。

在 HTML 中以“反应式”形式使用自定义验证器的方法是什么?

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    您的空白验证器不正确,试试这个 -

    import { AbstractControl, ValidatorFn } from '@angular/forms';
    
    @Directive({
        selector: '[appWhitespaceValidator]',
        providers: [{ provide: NG_VALIDATORS, useExisting: NoWhitespaceDirective, multi: true}]
    })
    export class NoWhitespaceDirective implements Validator {
    
        validate(control: AbstractControl): { [key: string]: any } {
            const isWhitespace = (control.value || '').trim().length === 0;
            const isValid      = !isWhitespace;
            return isValid ? null : { 'whitespace': true };
        }
    }
    

    【讨论】:

    • 在 html 中使用“反应式”表单的方法是什么?
    • 对不起,我不知道!
    【解决方案2】:

    您的空白验证器指令应该是:-

    import { AbstractControl, ValidatorFn } from '@angular/forms';
    
    @Directive({
        selector: '[appWhitespaceValidator]',
        providers: [{ provide: NG_VALIDATORS, useExisting: WhitespaceValidatorDirective , multi: true}]
    })
    export class WhitespaceValidatorDirective implements Validator {
    
        validate(control: AbstractControl): { [key: string]: any } {
            const isValid      = !control.value || (!control.value.startsWith(' ') && !control.value.endsWith(' '));
            return isValid ? null : { 'whitespace': true };
        }
    }
    

    像这样使用它:-

    <input type="text" id="name" name="getBlogTitle" [(ngModel)]="hero.name" #name="ngModel" appWhitespaceValidator>
    

    对于错误:-

    <div *ngIf = "getBlogTitle.errors?.whitespace">
      No spaces are allowed.
    </div>
    

    文档链接

    使用Existing、multi 和其他依赖注入提供程序:- https://angular.io/guide/dependency-injection-providers

    如何在没有指令的情况下添加自定义验证器:-

    https://codecraft.tv/courses/angular/advanced-topics/basic-custom-validators/

    (NG_VALIDATORS) 将成为此链接的一部分。

    说明:

    这个类是一个指令,因为@directive 装饰器可以用作任何表单元素的属性来验证输入,可以像我们上面在输入标签上使用的属性一样。这类指令在 Angular 中称为属性指令。唯一的事情是这个指令正在实现验证器类。

    当你想在表单中添加自定义验证器时,你必须提供 NG_VALIDATORS,useExisting 告诉我们使用我们的类作为验证器,multi 是告诉我们也可以有其他验证器,即可以是多个自定义验证器。所以提供者数组可以有类似的提供者:[{提供:NG_VALIDATORS,useExisting:NoWhitespaceDirective,multi:true},{提供:NG_VALIDATORS,useExisting:NoSpecialCharacterDirective,multi:true}]

    有一种方法可以让它在没有指令的情况下工作,你可以直接添加自定义验证器。视情况而定。如果你想创建一个验证器,它应该在你的应用程序中以各种形式提供,你可以使用指令。如果它是针对特定形式的,您可以在该组件中创建一个自定义验证器并附加它。

    验证码有问题:-

    您在输入任何内容后立即检查 (control.value || ''),您将获得正确的值而不是空白字符串。所以假设你输入'abc',然后你调用trim,它将把它转换成'abc'.length === 0。这会说假,因为它的3。那么你设置的有效!以上结果。所以 isValid 将变为 true,您的验证将失败。

    【讨论】:

    猜你喜欢
    • 2017-04-12
    • 2019-05-04
    • 2019-01-25
    • 2020-12-05
    • 1970-01-01
    • 2022-01-09
    • 2020-09-07
    相关资源
    最近更新 更多