Require one from two fields using Angular 2

后端 未结 4 1739
感情败类
感情败类 2020-12-29 09:02

I\'m trying to create a contact form. The form looks like this:

4条回答
  •  被撕碎了的回忆
    2020-12-29 09:45

    Slightly refactored Florian's answer for the lazy as it was making ts-sonar angry (cognitive-complexity rule):

    const isFieldEmpty = (fieldName: string, fg: FormGroup) => {
        const field = fg.get(fieldName).value;
        if (typeof field === 'number') { return field && field >= 0 ? true : false; }
        if (typeof field === 'string') { return field && field.length > 0 ? true : false; }
    };
    
    export function atLeastOne(...fields: string[]) {
      return (fg: FormGroup): ValidationErrors | null => {
        return fields.some(fieldName => isFieldEmpty(fieldName, fg))
          ? null
          : ({ atLeastOne: 'At least one field has to be provided.' } as ValidationErrors);
      };
    }
    

提交回复
热议问题