【问题标题】:how to validate input field which contains object如何验证包含对象的输入字段
【发布时间】:2021-12-13 22:32:22
【问题描述】:

如何检查所需的输入字段是否为空,formControl 无法读取对象...

  public discountParamsForm = new FormGroup({
     name: new FormControl('', Validators.required),
     type: new FormControl('', Validators.required),
     status: new FormControl('', Validators.required),
     value: new FormControl('', [Validators.required, Validators.pattern(/^([0-9]{1,2}){1}(\.[0-9]{1,2})?$/),
       Validators.min(1), Validators.max(100)]),
     dateInput: new FormControl('', Validators.required),
     categorySelect: new FormControl('', Validators.required)
  });

<input formControlName="dateInput" fullWidth type="text" [(ngModel)]="dateRange"
           nbInput placeholder="{{pickDateUI}}" [nbDatepicker]="datepicker">
    <nb-rangepicker (rangeChange)="onDateChange($event)" format="yyyy-MM-dd" #datepicker></nb-rangepicker>

console.log for value and discountparamsform

UI

【问题讨论】:

  • 使用 required 时,您的输入不能为空并抛出错误。你是什​​么意思:字段无法读取对象...,意思是这个 ....
  • @Rana 请检查截图,dateInput 包含对象,我认为 formGroup 无法验证对象,所以我需要解决方案。

标签: javascript html angular forms nebular


【解决方案1】:

从不,从不在同一标签中使用 [(ngModel)]formControlName

好吧,使用custom Validator

discountParamsForm = new FormGroup({
    ...
    dateInput: new FormControl('', this.validatorRange()),
})

validatorRange(){
  return (control:AbstractControl)=>{
     if (!control.value.start)
         return {error:'start date is mandatory'}
     if (!control.value.end)
         return {error:'end date is mandatory'}
  }
}

看到控件始终是一个具有“start”和“end”属性的对象——所以总是有值,所以在自定义验证器中我们检查这个属性是否有值——

【讨论】:

    【解决方案2】:

    这里有几件事,您正在查看表单对象本身。可以在控制台的图片上看到,整个表单是INVALID

    如果要查看表单中是否有某个字段可以使用get方法。

    在你的组件中

    this.discountParamsForm.get('name');
    

    这会返回一个 FormControl 对象,并具有有效/无效等值以及许多其他使用完整指标的值。

    你可以在你的组件中添加一个getter方法来检查你的html。

    get name() {
      return this.discountParamsForm.get('name');
    }
    
    <input [ngClass]="{'my-invalid-class': name.invalid}"
    

    由于我们有一个getter方法,我们不需要直接检查表单,我们可以很容易地访问父表单内的控件。

    【讨论】:

      猜你喜欢
      • 2011-10-04
      • 2020-12-19
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多