有条件地应用Angular 6 Compose Validator

时间:2018-10-22 05:09:36

标签: angular angular-reactive-forms

在我的应用程序中,我想有条件地应用组合验证器和相应的验证器。我使用了自定义验证程序,但没有成功。

{
    "coord": {
        "lon": 90.36,
        "lat": 23.79
    },
    "weather": [
        {
            "id": 721,
            "main": "Haze",
            "description": "haze",
            "icon": "50d"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 304.15,
        "pressure": 1013,
        "humidity": 62,
        "temp_min": 304.15,
        "temp_max": 304.15
    },
    "visibility": 3000,
    "wind": {
        "speed": 4.1,
        "deg": 330
    },
    "clouds": {
        "all": 20
    },
    "dt": 1540182600,
    "sys": {
        "type": 1,
        "id": 7879,
        "message": 0.0056,
        "country": "BD",
        "sunrise": 1540166342,
        "sunset": 1540207601
    },
    "id": 1337178,
    "name": "Dhaka District",
    "cod": 200
}
  1. 如果国家/地区为“美国”且年龄小于18岁,则必须提供dependentName,并且最大长度应为20。
  2. 如果国家/地区不是“ America”(美国)以外的国家,则不必提供dependentName字段,但maxlength应该为20。

请帮助。

1 个答案:

答案 0 :(得分:0)

定义您的客户验证器服务,并在formBuilder中使用它,如下所示

dependentName: ['',  [Validators.required, customValidationService.checkLimit(1,maxValue)]], /// provide your limit in place of minvalue and maxValue , like checkLimit(1,99)

在您的** customValidationService **

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

export class customValidationService {
   static checkLimit(min: number, max: number): ValidatorFn {
    return (c: AbstractControl): { [key: string]: boolean } | null => {
        if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
            return { 'range': true };
        }
        return null;
    };
  }
}

dependentName: [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])]