gpt4 book ai didi

angular - 为什么我的 formGroup 验证器没有按预期工作?

转载 作者:太空狗 更新时间:2023-10-29 16:54:56 25 4
gpt4 key购买 nike

如果我像这样使用 Angular 电子邮件验证器,我正在尝试进行表单验证并遇到一些问题:

<input type="email" class="mail" email name="emailField"  [(ngModel)]="email" #emailField="ngModel">

并通过formGroup将其放入表单中:

<form  [formGroup]="myForm" (ngSubmit)="onSubmit(f.value)" >

    <input type="email" class="mail" email name="emailField"  [(ngModel)]="email" #emailField="ngModel">
<div class="emailinvalid" *ngIf="emailField.invalid && emailField.touched">
<span *ngIf="emailField.hasError('email')">
Please enter the correct email, this email not valid.
</span>
</div>
<br>
</form>

这样电子邮件验证就不起作用了,所以我正在寻找修复它的方法,这是我的 ts 代码:

export class ContactComponent  {


myForm: FormGroup;
email: string;
username: string;
surname: string;
message: string;

constructor(fb: FormBuilder) {
this.myForm = fb.group({
'username': ['', Validators.required],
'surname': ['', Validators.required],
'message': ['', Validators.required],

});
}
}

usernamesurname 和我在上面的表单 (formGroup) 中使用的其他输入,我只是将其剪掉以稍微清理示例中的代码。

最佳答案

您似乎奇怪地混合了模板和 react 形式。我建议您使用响应式(Reactive)表单和内置验证器 email,同时删除任何 ngModel

constructor(private fb: FormBuilder) {
this.myForm = fb.group({
username: ['', Validators.required],
surname: ['', Validators.required],
message: ['', Validators.required],
email: ['', Validators.email]
});
}

然后模板看起来像这样:

<form  [formGroup]="myForm" (ngSubmit)="onSubmit(f.value)" >  
<input formControlName="username" >
<!-- more fields here -->
<input formControlName="email" >
<span *ngIf="myForm.hasError('email', 'email') && myForm.get('email').touched">
Please enter the correct email, this email not valid.
</span>
</form>

DEMO (为了清楚地显示验证器,我删除了touched)

关于angular - 为什么我的 formGroup 验证器没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45216306/

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