gpt4 book ai didi

javascript - Angular2 - 有条件创建的输入字段的表单验证

转载 作者:太空狗 更新时间:2023-10-29 18:14:23 25 4
gpt4 key购买 nike

我正在创建一个简单的表单,用户可以在其中选择两个可能的值,即 LocalForeigner。如果用户什么都不选择,它会使表单的值无效。如果用户选择 Local,表单将变为 valid。如果用户选择 Foreigner,则会出现一个新字段,用于将国家/地区作为用户输入,这也是必需的。如果用户在国家/地区输入字段中未输入任何内容,这会使表单无效

我尝试创建如下表单:

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {Control,ControlGroup,FormBuilder,FORM_DIRECTIVES,Validators} from 'angular2/common';

@Component({
selector: 'app',
template: `
<form [ngFormModel]="form" >
<select [ngFormControl]="nationalityCtrl" >
<option *ngFor="#nationality of nationalities" [value]="nationality" >{{nationality}}</option>
</select><br>
<input *ngIf="form.value.nationality == 'Foreigner'" type="text" [ngFormControl]="countryCtrl" placeholder="Country Name" />
<button class="btn btn-primary" [disabled]="!form.valid" >Submit</button>
</form>
`,
directives: [FORM_DIRECTIVES]
})
class MainApp{
public nationalities = ["Foreigner","Local"];
public form:ControlGroup;
public nationalityCtrl:Control;
public countryCtrl:Control;

constructor(private _fb:FormBuilder){
var self = this;

this.nationalityCtrl = new Control("",Validators.compose([Validators.required]));
this.countryCtrl = new Control("",Validators.compose([function(control:Control){
if(self.nationalityCtrl.value == "Foreigner" && !control.value){
return {invalid: true};
}
}]));

this.form = this._fb.group({
nationality: this.nationalityCtrl,
country: this.countryCtrl
});
}
}
bootstrap(MainApp);

但是一旦我选择了 Foreigner 选项,我就会在控制台上收到以下错误:

EXCEPTION: Expression '!form.valid in MainApp@6:36' has changed after it was checked. Previous value: 'false'. Current value: 'true' in [!form.valid in MainApp@6:36]

我在 plunker here 上重现了这个问题您可以在控制台上看到错误消息。

最佳答案

我会为整个表单定义一个全局验证器,因为您的验证器取决于两个字段:

this.form = this._fb.group({
nationality: this.nationalityCtrl,
country: this.countryCtrl
}, {
validator: (control:Control) => {
var nationalityCtrl = control.controls.nationality;
var countryCtrl = control.controls.country;
if(nationalityCtrl.value == "Foreigner" && !countryCtrl.value){
return {invalid: true};
}
}
});

查看此插件:https://plnkr.co/edit/Cksiv2UFbWoVJv2VwPwh?p=preview .

有关详细信息,请参阅此问题:

关于javascript - Angular2 - 有条件创建的输入字段的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36399934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com