sho*_*pik 18 validation angular
我正在尝试进行表单验证并遇到一些问题,如果我使用这样的角度电子邮件验证器:
<input type="email" class="mail" email name="emailField" [(ngModel)]="email" #emailField="ngModel">
Run Code Online (Sandbox Code Playgroud)
并通过formGroup将其置于表单中:
<form [formGroup]="myForm" (ngSubmit)="onSubmit(f.value)" >
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
以这种方式电子邮件验证不起作用,所以我正在寻找修复它的方法,这是我的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],
});
}
}
Run Code Online (Sandbox Code Playgroud)
username
,surname
以及我在上面的表单(formGroup)中使用的其他输入,我只是将其剪掉以清除代码中的一些示例.
AJT*_*T82 30
你好像混合了模板和反应形式.我建议你使用反应形式和内置验证器email
,同时删除任何ngModel
.
constructor(private fb: FormBuilder) {
this.myForm = fb.group({
username: ['', Validators.required],
surname: ['', Validators.required],
message: ['', Validators.required],
email: ['', Validators.email]
});
}
Run Code Online (Sandbox Code Playgroud)
然后模板看起来像这样:
<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>
Run Code Online (Sandbox Code Playgroud)
DEMO(只是为了清楚地显示验证器,我已经删除了touched
)
您可以拥有validator.ts文件
const pureEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
export const regexValidators = {
phone: '[\+][0-9() ]{7,}$',
email: pureEmail,
};
Run Code Online (Sandbox Code Playgroud)
并在您的组件中使用,如:
this.myForm = fb.group({
'username': ['', Validators.required],
'surname': ['', Validators.required],
'message': ['', Validators.required],
'email': ['', [Validators.required,Validators.pattern(this.validators.email)]]
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19826 次 |
最近记录: |