【问题标题】:Angular custom reactive forms validator doesn't workAngular 自定义响应式表单验证器不起作用
【发布时间】:2020-10-16 04:57:44
【问题描述】:

我正在尝试为日期范围检查实现自定义角度验证器。

验证器本身正常工作并返回验证错误。但是,客户端似乎没有发生任何事情 - 没有显示错误并且表单被认为是有效的。我尝试了对这段代码的各种更改,但没有任何乐趣。

有什么想法可以尝试吗?


HTML:

<div class="alert-danger" *ngIf="form.controls.creditCheckDate.errors?.dateRange">
    Date should be from 1/1/2000 to Today.
</div>

.ts:

const controlsConfig = {
    creditCheckDate: ['', [Validators.required,
                           CustomValidators.dateRange(new Date(2000, 1), new Date(Date.now()))]]
};

return this.fb.group(controlsConfig);

验证器:

static dateRange(minDate: Date | null, maxDate: Date | null): ValidatorFn {
    return (c: AbstractControl): ValidationErrors | null => {
        const validationError = { dateRange: true };

        if (!c.value) {
            return null;
        }

        const timestamp = Date.parse(c.value);
        if (isNaN(timestamp)) {
            return validationError;
        }

        const date = new Date(timestamp);
        if ((minDate && minDate > date) || (maxDate && maxDate < date)) {
            return validationError;
        }

        return null;
    };
}

【问题讨论】:

  • 尝试添加*ngIf="NameOfYourForm?.hasError('dateRange')"
  • @Kardon63 谢谢,不幸的是它仍然不起作用。我尝试在控件更改事件中将表单记录到控制台中,即使验证器返回错误,表单也被认为是有效的,因此控件中没有错误。
  • 你能创建一个堆栈闪电战吗?

标签: angular typescript validation frontend customvalidator


【解决方案1】:

请看一下我的代码。

HTML

<form [formGroup]="testForm">
  <div class="row">
    <div class="col-xs-12 col-12 col-md-4 form-group">
      <input
        type="text"
        placeholder="Datepicker"
        class="form-control"
        bsDatepicker
        formControlName = "date"
      />
    </div>
    <div *ngIf="testForm.controls.date.invalid && (submitted)" class="text-danger">
        <small *ngIf="testForm.controls.date.errors?.required">
           Date is required
         </small>
       <small *ngIf="testForm.controls.date.errors?.dateRange">
         Date is invalid
       </small>
     </div>
  </div>
  <button type="button" (click)="onSubmit()">Submit</button>
</form>

TS

 import { Component } from "@angular/core";
    import {
      AbstractControl,
      FormGroup,
      FormControl,
      ValidationErrors,
      ValidatorFn,
      Validators
    } from "@angular/forms";
    
    @Component({
      selector: "app-root",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      testForm: FormGroup;
      submitted: boolean;
    
      constructor() {
        this.testForm = new FormGroup({
          date: new FormControl("", [Validators.required, this.dateRange(new Date(2000, 1), new Date(Date.now()))])
        });
        this.submitted = false;
      }
    
      dateRange(minDate: Date | null, maxDate: Date | null): ValidatorFn {
        return (c: AbstractControl): ValidationErrors | null => {
          const validationError = { dateRange: true };
    
          if (!c.value) {
            return null;
          }
    
          const timestamp = Date.parse(c.value);
          if (isNaN(timestamp)) {
            return validationError;
          }
    
          const date = new Date(timestamp);
          if ((minDate && minDate > date) || (maxDate && maxDate < date)) {
            return validationError;
          }
    
          return null;
        };
      }
    
      onSubmit() {
        this.submitted = true;
        console.log(this.testForm);
      }
    }

我已经在代码沙箱中尝试过您的代码,它似乎工作正常。 https://codesandbox.io/s/suspicious-http-11288

【讨论】:

  • 非常感谢您抽出宝贵的时间来制作它!我真的很困惑为什么那个有效,而我的却没有。我开始检查我的代码和您创建的沙箱之间有什么不同,然后发现有人在另一个验证器中重置表单的所有错误。您的回答帮助我解决了这个问题,谢谢!
  • 很高兴它有帮助!
【解决方案2】:

结果证明我没有提供所有信息。问题是有人在其他验证器中重置表单的所有错误。这是一种糟糕的做事方式,因为我找了很长时间都找不到它,但它就在那里。当我找到并修复它时,一切都开始按预期工作。

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2017-08-28
    • 1970-01-01
    • 2018-09-19
    • 2019-03-08
    • 1970-01-01
    • 2020-01-13
    • 2019-01-13
    • 2019-11-15
    相关资源
    最近更新 更多