FormGroup 不会对带有服装验证器的验证器做出反应

时间:2021-05-25 09:09:44

标签: javascript angularjs

我正在尝试使用自定义验证器将整个 fromGroup 设置为无效,这似乎不起作用...

下面代码的目标是比较 fromGroup 的两个实例。

  • 如果它们匹配,则意味着没有进行任何更改,因此必须是 无效。
  • 否则它不匹配意味着已经进行了更改,因此必须是 有效。

我的变量 isValid 在我记录时正常工作。它根据变化变成真或假。

但我无法使 from 无效,我尝试了很多方法来形成文章和堆栈溢出,其中有一个 stackblitz,但我似乎也不起作用。

喜欢Angular 6 Required only one field from many fields Reactive Form中的this.updateCyclistForm.setErrors({ 'invalid': true});

我看到很多类似的帖子都有 this one 使用控件,但这里不是这种情况。

public updateCyclistForm: FormGroup
public savedStateOfForm: FormGroup

...

constructor(...) {
    ...
    this.savedStateOfForm = new FormGroup({
        status: new FormControl(this.currentReg.status, []),
        role: new FormControl(this.currentReg.role, []),
        passes: new FormControl({ data: this.passesUID }, [])
    })
    this.updateCyclistForm = new FormGroup({
        status: new FormControl(this.currentReg.status, []),
        role: new FormControl(this.currentReg.role, []),
        passes: new FormControl({ data: this.passesUID }, [])
    })
    this.updateCyclistForm.setValidators(this.isValid(this.savedStateOfForm));
}
    
...

isValid = (clone: FormGroup): ValidatorFn => {
    return (group: FormGroup): ValidationErrors => {
        let isValid = JSON.stringify(clone.value) != JSON.stringify(control.value)
        group.setErrors({ 'valid': isValid });
        this.updateCyclistForm.setErrors({ 'valid': isValid });
        return
    }
}

HTML

<button type="submit" [disabled]="!updateCyclistForm.valid">Save</button>

按钮永远不会被禁用,为什么?我做错了什么?

编辑:

我也尝试使用与@Adam 的回答类似的内容。这让我的 button 终身残疾。

  isValid = (clone: FormGroup): ValidatorFn => {
        return (group: FormGroup) : ValidationErrors => {
            return {
                invalid: JSON.stringify(clone.value) != JSON.stringify(group.value) ? true : null
              }
        }
    }

2 个答案:

答案 0 :(得分:1)

setValidators 必须接受返回 ValidatorFn(或 null)的 ValidationErrors 函数

constructor() {

   // ...

   this.updateCyclistForm.setValidators(this.updateCyclistValidator);
}


...

updateCyclistValidator(ctrl: FormGroup) {
   const valid = // run your validation uisng the values in ctrl

   // if there are no errors, you MUST return null
   if(valid) return null;

   // return your errors, for example:
   return {
     role: 'choose a role'
   }
    
}

验证器返回的错误是否存在会告诉 angular 您的表单是否有效。

答案 1 :(得分:0)

感谢@Adam的帮助

这是出来的解决方案

isValid = (clone: FormGroup) => {
    return (group: FormGroup) => {
        return JSON.stringify(clone.value) != JSON.stringify(group.value) ? null : { invalid: JSON.stringify(clone.value) != JSON.stringify(group.value) }
    }
}