ReactiveForm 中的 Angular Material 时间输入验证

问题描述 投票:0回答:1

我正在 Angular 17 中使用 Material。 假设我有一个反应式表单的示例,其中有 2 个时间类型的输入。

[minHour, maxHour] 应该是小时的间隔范围,比方说 [09:00 , 13:00]。

HTML [我的时间.component.html]

<form [formGroup]="timeFormGroup" (ngSubmit)="save()">
   
 <div style="display:flex">  
  <mat-form-field style="width: 100px;" appearance="outline">                         
   <mat-label>Min Hour</mat-label>
     <input type="time" matInput formControlName="minHour">
  </mat-form-field>                           

   <mat-form-field style="width: 100px;" appearance="outline">
      <mat-label>Max Hour</mat-label>
        <input type="time" matInput formControlName="maxHour">
   </mat-form-field>
 </div>
  ...
    <div>
       ...
       <button mat-flat-button color="accent" type="submit">Save</button>
    </div>

</form>

[TS] 我的时间.component.ts

import { Component, Inject, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input'
import { FormBuilder, Validators } from '@angular/forms';

....

@Component({
  selector: 'app-my-time',
  templateUrl: './my-time.component.html',
  styleUrl: './my-time.component.scss'
})
export class MyTimeComponent implements OnInit {

constructor(private fb: FormBuilder){}

  timeFormGroup = this.fb.group({
    minTime: ['', Validators.required],
    maxTime: ['', Validators.required]

  });



  ngOnInit(): void {

  }

  save() {
    console.log(this.timeFormGroup.value)
  }

}

我需要检查验证输入时是否遵守此范围。 当输入与 09:00 - 13:00 范围不同时,我还需要显示错误消息。

感谢任何愿意帮助我的人,特别是一些代码示例

angular angular-material angular-reactive-forms
1个回答
0
投票

我可能需要更多信息,但我会尝试使用我所拥有的信息。

自定义验证器

我将为此目的构建一个特定的验证器。

  timeFormGroup = this.fb.group({
    minTime: ['', [Validators.required, this._minTimeValidator('09:00')]],
    maxTime: ['', Validators.required]
  });

  private _minTimeValidator(minTime: string): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const inputTime = control.value as string

      if (!inputTime) {
        return null // If the control is empty, don't perform validation
      }

      const minTimeObj = new Date(`1970-01-01T${minTime}`)
      const inputTimeObj = new Date(`1970-01-01T${inputTime}`)

      return inputTimeObj >= minTimeObj ? null : { minTime: true }
    }
  }

这样,如果用户选择小于

09:00
,minTime 将是错误的。您可以对 maxTime 执行相同的操作。

动态设置验证器

如果您需要根据最短(或最大)时间设置最短(或最大)验证器。您可以订阅 formControl 更改

具有取消订阅“proTip”逻辑

protected _unsubscribe$: Subject<void> = new Subject()

ngOnInit(): void {
  this.timeFormGroup.valueChanges
    .pipe(
      filter((event) => (event ? true : false)),
      takeUntil(this._unsubscribe$),
    )
    .subscribe((value) => {
      const minTime = value.minTime.split(':') // Could be useful
      const maxTime = value.maxTime.split(':') // Could be useful
      const minTimeControl = this.timeFormGroup.get('minTime')

      if (
        // Your logic : If true
      ) {
        const customTime = '09:00' // Whatever you like, use minTime or maxTime if you wish
        minTimeControl.setValidators(this._minTimeValidator(customTime))
      } else if (minTimeControl.validator) { // If we have validator
        minTimeControl.setValidators(null)
        minTimeControl.updateValueAndValidity()
      }
    })
}

ngOnDestroy(): void {
  this._unsubscribe$.next()
  this._unsubscribe$.complete()
}
© www.soinside.com 2019 - 2024. All rights reserved.