Angular 2: Apply Validator.required validation on some condition

前端 未结 4 663
轮回少年
轮回少年 2020-12-16 05:09

I have a angular 2 form wherein I have to make a field required on some condition like:

description:  [\'\', Validators.required]

This desc

4条回答
  •  心在旅途
    2020-12-16 05:51

    If descReq needs to be evaluated at run-time (rather than when its initialized), then perhaps you should create a custom validator:

    import { ValidatorFn, AbstractControl } from '@angular/forms';
    interface ValidationResult {
        [key:string]:boolean;
    }
    function customValidator(condition: { required:boolean }) {
         return (control: AbstractControl) :ValidationResult  => {
             return condition.required && 
                 (control.value == undefined || 
                  control.value == null || 
                  control.value.trim() =='') ? 
                  {
                     'required': true
                  }: null;
    
           }
    
    }
    

    Use like this:

    description:  ['', customValidator(this.reqd)]
    

    where reqd has been initialized earlier, and maybe even data-bound:

    reqd = { required: false };
    

提交回复
热议问题