【问题标题】:Model Driven Form validation not working模型驱动表单验证不起作用
【发布时间】:2016-08-08 00:11:17
【问题描述】:

在进行模型驱动表单验证时开始变得令人沮丧,但现在 2 天仍然无法工作。

据我了解,Angular2 beta 仍然存在一些错误。我在 https://angular.io/docs/ts/latest/guide/forms.html 使用了来自 angular-io 的示例,在 Forms In angular2 使用了不同的示例。我公司的两个程序员告诉我,他们都没有任何表单示例。

谁能提供我可以尝试的验证工作示例?

【问题讨论】:

标签: angular angular2-forms


【解决方案1】:

正如您已经知道的那样,仍有一些与 angular2 表单相关的未决问题需要验证。但是经过大量搜索后,我发现很少有人在工作,现在正在发布作为答案 -

首先,对于验证,您必须使用 ngControl ,您也可以使用 ngModel ,即 angular2 的两种方式绑定来获取表单值,毫无疑问,我们只能使用 ngControl 进行验证和表单值。但最好使用单独的。

使用 ngControl 进行验证。 Angular 提供了默认验证器来检查验证,我们也可以根据需要创建自定义验证器,并可以在验证中使用(ngControl)。如果我们要创建模型驱动表单,即我们必须使用 new Control() 为每个输入创建新控件。对于控制、控制组和验证,请参阅这篇最佳文章

这是使用表单控件的基本示例:

this.CreateGroup = fb.group({
            'name': new Control(this.demoInfo.name, Validators.required),
            'password': new Control(this.demoInfo.password, Validators.required),
            'select': new Control(this.demoInfo.select, Validators.required)
        })

这里我有三个输入,分别命名为 name、password、select。以及相应的我已经提到了它们的值和验证器(默认验证)。

<input type="text" [(ngModel)]='demoInfo.name' ngControl='name'>

这是我们如何将 ngControl 定义为 HTML 端。

form in angular2 with validation.的工作演示

【讨论】:

    【解决方案2】:

    关键是建立对照组:

    this.form = fb.group({
                "firstName": ['', Validators.required],
                "streetAddress": ['',Validators.required],
                "zip": ['', Validators.compose([zipValidator])],
                "type": ['home']
            });
    

    以下是一些带有验证的表单示例:

    http://www.syntaxsuccess.com/angular-2-samples/#/demo/form 更多信息在这里: http://www.syntaxsuccess.com/viewarticle/forms-and-validation-in-angular-2.0

    这里也是一个动态表单的例子:

    http://www.syntaxsuccess.com/angular-2-samples/#/demo/survey http://www.syntaxsuccess.com/viewarticle/dynamic-form-in-angular-2.0

    【讨论】:

      猜你喜欢
      • 2014-09-13
      • 1970-01-01
      • 2016-09-11
      • 2017-03-18
      • 2018-05-31
      • 1970-01-01
      • 2021-12-01
      • 2017-09-17
      相关资源
      最近更新 更多