1

表单中有建筑面积和出租面积
想要验证出租面积必须小于等于建筑面积应怎么写啊

小白求教

  add = this.form.group({
    buildingId: [null, [Validators.required]],
    roomNo: [null, [Validators.required]],
    roomResourceType: ['1'],
    roomBuildAcreage: [null, [Validators.required]],
    roomEquipments: [null],
    roomDecorateState: ['1'],
    roomRentedAcreage: [null, [Validators.required, this.validateRentedAcreage,rentedAcreageValidator(add)]],
    roomResourceState: ['1', [Validators.required]],
    isCharge: ['1', [Validators.required]],
    heatingCost: [null, [Validators.required]],
    roomDesc: [null],
  });
2018-12-04 提问
2 个回答
2

给个大概吧:

/** 自定义验证器 */
checkRented(control:FormControl) {
    let form:FormGroup = this.add
    /** 出租面积小于建筑面积即通过此验证器 */
    if(form && form.get('roomDecorateState').value - control.value > 0){
        return null
    }
    /** 不通过验证,rentedErr 为表单错误标示,可以供后期判断错误类型 */
    return { rentedErr:true }
}

在构造表单的函数中:

let _checkRented = this.checkRented.bind(this)
this.add = this.form.group({
    /** 此处省略其他字段 */
    ...
    roomRentedAcreage: [null, [Validators.required, _checkRented]]
})

当发生错误时,可在模版上给出很明确当提示:

<ng-container *ngIf="add.get('roomRentedAcreage').dirty && add.get('roomRentedAcreage').hasError('rentedErr')">
    请确保出租面积小于输入的建筑面积
</ng-container>
0

roomBuildAcreage未填写时roomRentedAcreage设为只读
然后

 this.form.get('roomBuildAcreage').valueChanges
      .subscribe((acreage: number) => {
           this.form.get('roomRentedAcreage').setValidators(Validators.max(acreage))
      })

界面根据control的invalid提示

撰写答案

推广链接