【问题标题】:Angular2 (rc.5) setting a form to invalid with a custom validatorAngular2(rc.5)使用自定义验证器将表单设置为无效
【发布时间】:2016-09-07 06:14:50
【问题描述】:

我在其中一个字段上使用带有自定义验证器的模板驱动表单:

<button type="button" (click)="myForm.submit()" [disabled]="!myForm.valid" class="btn">Save</button>
<form #myForm="ngForm" (ngSubmit)="submit()">
   ...
   <input type="text"
                 class="validate"
                 [(ngModel)]="myDate"
                 name="myDate"
                 ngControl="myDate"
                 myValidator/>
</form>

我的验证器:

import { Directive, forwardRef } from '@angular/core'
import { NG_VALIDATORS, FormControl, Validator } from '@angular/forms'

function check(s: string) {
   ...
}

function customValidation() {
  return (c: FormControl) => {
    return check(c.value) ? null : {
      myValidator: false
    }
  }
}


@Directive({
  selector: '[myValidator ][ngModel],[myValidator ][formControl]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: forwardRef(() => MyValidator), multi: true }
  ]
})
export class MyValidator implements Validator {

  validator: Function

  constructor() {
    this.validator = customValidation()
  }

  validate(c: FormControl) {
    return this.validator(c)
  }
}

在球场上一切都很好。唯一的问题是验证器将字段设置为无效,表单未设置为无效,因此保存按钮未禁用。我不明白为什么。我想我忘记了验证器和表单之间的链接。

我正在使用 angular_forms 0.3.0

这是一个 plunkr :http://plnkr.co/edit/qUKYGFNLyjh6mNiqYY5I?p=preview,它似乎确实有效......(虽然是 rc.4)

【问题讨论】:

  • 你用 RC.6 试过了吗?
  • 我还没有,因为我的一些依赖项(ng2-select by instance)在 rc.6 中仍然不兼容。所以我又在 rc.5 中停留了几天。这里有什么奇怪的地方吗?
  • 你可以试试 Plunker。有一些与表单相关的更改和修复。
  • 对不起,我刚刚编辑了

标签: forms angular


【解决方案1】:

我已将您的代码放入 plunkr。

http://plnkr.co/edit/qUKYGFNLyjh6mNiqYY5I?p=preview

而且效果很好。您可以检查代码的其他部分。具体来说,我有自己的 check 功能。

function check(s: string) {
  if(s.length > 0){
    return true;
  }else{
    return false;
  }
}

您是否初始化了 myDate 值?如果它没有被初始化,我会在开始时得到一个有效的表单。

ngOnInit() {
    this.myDate = ''
  }

【讨论】:

  • 你的代码和plunkr有区别吗?
  • 只有一个区别,就是plunkr有disableDeprecatedForms(),provideForms(),我用的是FormsModule
  • 我现在看到它在 RC4 中,也许这就是原因。
  • 我在 rc.6 中使用 angular_forms 在 2.0.0 rc.6 中进行了尝试,并且效果也很好。我有点困惑。
  • 暂时有没有办法强制表单无效?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 2016-12-04
  • 1970-01-01
  • 2017-03-03
相关资源
最近更新 更多