标签: angular-reactive-forms

使用 Angular Reactive Forms 验证年龄是否超过 18 岁

有没有办法在用户使用 Angular 验证器输入出生日期时检查用户是否已年满 18 岁?

我的表格如下所示:

<form [formGroup]="authForm" (ngSubmit)="submitForm()">
    <label>Date of birth</label>
    <input formControlName="day" maxlength="2" placeholder="DD" type="text" />
    <input formControlName="month" maxlength="2" placeholder="MM" type="text" />
    <input formControlName="year" maxlength="4" placeholder="YYYY" type="text" />
    <button [disabled]="!authForm.valid" type="submit"> Check age </button>
</form>
Run Code Online (Sandbox Code Playgroud)

然后我在 TS 文件中设置这些验证器:

if (this.authType === 'register') {
    this.authForm.addControl('year', new FormControl('', [Validators.required, Validators.maxLength(4), Validators.minLength(4)]));
    this.authForm.addControl('month', new FormControl('', [Validators.required, Validators.maxLength(2)]));
    this.authForm.addControl('day', new FormControl('', [Validators.required, Validators.maxLength(2)]));
 }
Run Code Online (Sandbox Code Playgroud)

因此,如果验证器中满足上述条件,则该按钮将启用。但我还需要在启用之前检查输入的日期是否超过 18 岁。这看起来很棘手,因为日期是通过 3 个输入(dd、mm、yyyy)输入的。在这种情况下,我无法使用输入日期标签。任何建议或意见表示赞赏。谢谢!

PS 感谢您对使用 MomentJS 的所有建议。我已经在应用程序的其他地方使用它,所以我也会在这里使用它。

validation date angular angular-reactive-forms

2
推荐指数
1
解决办法
1万
查看次数

如何使整个表单只读 Angular2

我想对表单内的所有控件进行只读操作,有什么方法可以在表单级别属性中实现此目的。我可以对每个控件应用只读并实现这一点,但形式非常复杂。

angular angular-reactive-forms

2
推荐指数
1
解决办法
8597
查看次数

如何使用 Angular5 检查表单控件的更改

我使用反应式表单,我有多个输入,我想为三个输入显示一个错误,验证是;字段为必填字段,不得输入空格。

\n\n

组件.html:

\n\n
    <form [formGroup]="contratoForm" class="campo-form">\n        <div class="campoFormulario">\n            <label class="etiquetaFormulario" for="txtCodigoContrato">C\xc3\xb3digo contrato</label>\n            <div style="display:inline-block; position: relative;"  class="control">\n                <input [formControl]="txtCodigoContrato" type="text" id="txtCodigoContrato" name="txtCodigoContrato" class="cajaTexto ancho80" />\n                <span>/</span>\n            </div>                \n            <div style="display:inline-block; position: relative;" class="control">                \n                <input [formControl]="txtCodigoContrato2" type="text" id="txtCodigoContrato2" name="txtCodigoContrato2" class="cajaTexto ancho80" />              \n            </div>\n        </div>\n        <div class="campoFormulario">\n            <label class="etiquetaFormulario" for="txtContrato">Contrato</label>\n            <div style="display:inline-block; position: relative;" class="control">\n                <input [formControl]="txtContrato" type="text" id="txtContrato" name="txtContrato" class="cajaTexto ancho350" />\n\n            </div>\n        </div>\n         <div *ngIf="((!txtCodigoContrato.valid && (txtCodigoContrato.dirty || txtCodigoContrato.touched)) && (txtCodigoContrato.hasError(\'required\') || txtCodigoContrato.hasError(\'hasWhites\')))\n                ||\n                ((!txtCodigoContrato2.valid && (txtCodigoContrato2.dirty …
Run Code Online (Sandbox Code Playgroud)

custom-validators angular angular-reactive-forms

2
推荐指数
1
解决办法
2万
查看次数

通过 Switch Case 进行 Angular ReactiveForm 错误处理

我有一个反应式表单,其中我使用 ngif 验证不同的字段。

例如:

  <mat-form-field>
  <input  matInput formControlName="name" placeholder="Name">
  <mat-error 
  *ngIf="personForm.get('name').hasError('required')">Name is 
   empty</materror>
  <mat-error *ngIf="personForm.get('name').hasError('minlength')">Needs more 
   than 3 characters</mat-error>
  </mat-form-field>
Run Code Online (Sandbox Code Playgroud)

是否有可能在 switch case 语句中做同样的事情以及如何继续这样做?

我想象了这样的事情

validateErrors {
  switch(errorHandling) {
  case 1: 'Name is empty';
  case 2: 'Needs more than 3 characters';
  }
}
Run Code Online (Sandbox Code Playgroud)

如何让 mat-errors 显示这些不同的情况?任何指导将不胜感激,谢谢!

error-handling switch-statement angular angular-reactive-forms angular-forms

2
推荐指数
1
解决办法
2702
查看次数

Angular 2 Reactive Forms 仅从更改的控件中获取值

我有一个包含所有输入的动态创建的表单。我正在订阅更改,但是当某个控件发生更改时,我会从所有控件中获取值,因此我真的不知道哪个控件发生了更改。是否可以使用 valueChanges 函数仅从更改的控件中获取更改的值?

该表单非常大,因此将每个控件都订阅到 valueChanges 不是一种选择。

该函数目前如下所示:

checkForValueChanges() {
    this.metadataForm.valueChanges.subscribe(controls => {
        // how to get the changed control form name here ?
    });
}
Run Code Online (Sandbox Code Playgroud)

由于项目非常大,我只是做了一个简单的例子来展示我的问题: StackBlitz example 您可以在控制台中看到我得到的结果是所有控件,而不仅仅是更改的控件。

angular angular-reactive-forms

2
推荐指数
1
解决办法
4915
查看次数

角反应形式

我是 Angular 5 的新手。我目前正在研究 Angular Reactive 表单。我有一个下面的 JSON 结构,从 FORM 获取值后需要将其发回 REST API。

JSON 结构:

 {
  "empDesg": "Sr Developer",
  "empID": 123,
  "empName": "Sam",
  "empSkills": [
                "Java",
                "Devops"
               ]
 }
Run Code Online (Sandbox Code Playgroud)

我设法将 empID、empName 和 empDesg 映射到 formcontrols;它们都将成为输入文本元素。我想使用 formcontrols 或 formarray 将 empSkills 映射到复选框(但不确定使用哪一个)-只有我被困住了。

我的 HTML 和组件类:

addEmp.component.html

 <form class="form-emp" [formGroup]="empForm">
             <div class="form-group row ">
                <label for="empID" class="col-sm-2 col-form-label">EmpID</label>
                <div class="col-sm-10">
                    <input type="text" formControlName="empID" name="empID" class="form-control" id="empID" placeholder="Employee ID">
                     <div *ngIf="empForm.controls.empID.invalid && empForm.controls.empID.touched">
                    <ngb-alert type="danger" [dismissible]="false">Employee ID is must</ngb-alert>
                </div>
                </div>

                </div>
                <div …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

2
推荐指数
1
解决办法
5449
查看次数

角度异步验证器的状态未反映在表单字段的错误状态中

我在一个字段上有一个异步验证器zip

zip: ['', {
            validators: [
              Validators.required,
              Validators.minLength(5),
              Validators.maxLength(5)
            ],
            asyncValidators: [
              adPostFormValidators.isValidZip(this.locationService)
            ]
          },
      ],
Run Code Online (Sandbox Code Playgroud)

但是,在我单击该字段之外之前,该字段似乎并未反映来自异步验证器的错误。例如,这是在我单击之前(这null是字段的错误状态):

在此输入图像描述

我知道异步验证器已经运行,因为我将其结果输出到控制台:

在此输入图像描述

然后,当我单击或失去焦点时,错误状态现在是准确的:

在此输入图像描述

但是,验证器没有再次运行,因为控制台中没有记录任何新内容。

angular angular-reactive-forms

2
推荐指数
1
解决办法
933
查看次数

反应式表单自定义验证器不显示 Angular6 中的错误

在此演示中,我为自定义验证器创建了一个示例表单,这里有“起始日期”和“截止日期”以及“起始时间”和“截止时间”,工作正常:对于“起始日期”和“截止日期”验证工作正常并显示错误消息。

问题:当选择相同的日期时,例如)2018 年 7 月 21 日作为起始日期,并且“To date e”和“In from Time”为 4:00 AM,“To Time”为 3:00AM,条件得到满足,但没有显示错误消息。在实施过程中出现了一些问题,任何人都可以帮我解决吗?

在 html 中,我给出了验证消息,但没有显示。

To Time:
<input type="time" formControlName="ToTime">
    <mat-error *ngIf="DaterForm.get('ToTime').hasError('InValidToTime')">FromTime Should be less than ToTime if choose a same date</mat-error>
Run Code Online (Sandbox Code Playgroud)

在组件中:

 DaterForm : FormGroup;

constructor(private fb:FormBuilder){
}
   ngOnInit(){

 this.DaterForm = this.fb.group(
{
  FromDate:['',[AppCustomDirective.fromDateValidator]], // validation working fine
  FromTime:[''],
  ToDate:['',[AppCustomDirective.ToDateValidator]],// validation working fine
  ToTime:['']
},{validator:[AppCustomDirective.timeValidator] // validation not working
}
Run Code Online (Sandbox Code Playgroud)

自定义验证:

import { AbstractControl, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms';

export class AppCustomDirective …
Run Code Online (Sandbox Code Playgroud)

angular2-forms angular angular-reactive-forms angular4-forms angular6

2
推荐指数
1
解决办法
3331
查看次数

异步验证器 (AsyncValidatorFn) 从不订阅

我写了一个自定义的表单验证器,但errors它只是有"_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": false, "source": {"_isScalar": false}, "operator": {}}, "operator": {"total": 1}并且表单永远不会有效。

这是我的验证器:

export function asyncEmailValidator(): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> => {
    return of(control.value).pipe(
      map(res => {
        return res && res.indexOf('example.de') < -1 ? { eMailUnavailable: true } : null;
      }),
      take(1), finalize(() => {})
    );
  };
}
Run Code Online (Sandbox Code Playgroud)

这是我如何使用它:

emailFormControl = new FormControl('', [
  Validators.required,
  Validators.email,
  asyncEmailValidator()
]);
Run Code Online (Sandbox Code Playgroud)

从调试中,我发现我检查 example.de 的地图块从未到达过,我不明白为什么。在显示内部返回之前使用和输出函数本身。

我在网上的多个示例中看到了这种结构,但它似乎对我不起作用。

我在用 @angular/forms 10.0.14

angular angular-reactive-forms angular-forms angular2-form-validation

2
推荐指数
1
解决办法
834
查看次数

错误 TS2739:“AbstractControl”类型缺少“FormControl”类型中的以下属性:registerOnChange、registerOnDisabledChange

我是 Angular 的新手,正在学习使用Angular 10的在线课程,但有一次卡住了。我正在尝试实现Reactive 表单。为此,我添加了一个新组件text-input。的代码text-input.component.ts如下:

import { Component, Input, Self } from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';

@Component({
  selector: 'app-text-input',
  templateUrl: './text-input.component.html',
  styleUrls: ['./text-input.component.css']
})
// We need to implement a control value accessor
export class TextInputComponent implements ControlValueAccessor {
  @Input() label: string;
  @Input() type = 'text';

  constructor(@Self() public ngControl: NgControl) {
    this.ngControl.valueAccessor = this;
  }
  writeValue(obj: any): void {
  }

  registerOnChange(fn: any): void {
  }

  registerOnTouched(fn: any): void …
Run Code Online (Sandbox Code Playgroud)

angular angular-reactive-forms

2
推荐指数
3
解决办法
2894
查看次数