我正在使用 FormGroup , FormBuilder 和 Validators 类来验证Angular2应用中的表单。
这就是我为电子邮件和密码验证定义所需验证规则的方法: -
export class LoginComponent implements OnInit {
loginFormGroup:FormGroup;
adminLoginmodel = new Admin('', '', '', 'Emailsss','Passwordsss');
constructor(
private route: ActivatedRoute,
private router: Router,
private _adminLogin: AdminLoginService,
fb: FormBuilder
){
this.loginFormGroup = fb.group({
'email' : [null, Validators.compose([Validators.required, Validators.email])],
'password': [null, Validators.required]
});
}
}
代码Validators.compose([Validators.required, Validators.email])
检查电子邮件字段是否为空以及提供的字符串是否为有效电子邮件。
但是,我不知道如何在不同情况下显示不同的验证消息。说
以下是我在html中显示验证消息的方式: -
<div class="input-group input-group-lg" [ngClass]="{'has-error':!loginFormGroup.controls['email'].valid && loginFormGroup.controls['email'].touched}">
<span class="input-group-addon"><i class="glyphicon glyphicon-user red"></i></span>
<input type="text" class="form-control" placeholder="Email" id="email" name="email" [formControl]="loginFormGroup.controls['email']" [(ngModel)]="adminLoginmodel.email"/>
</div>
<div class="alert alert-danger" *ngIf="!loginFormGroup.controls['email'].valid">You must add an email.</div>
如何在不同情况下显示不同的消息?
答案 0 :(得分:0)
import { Component } from '@angular/core';
import {FormControl, Validators} from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<input [formControl]="ctrl" />
<div *ngIf="ctrl.errors?.email">
Provided email is not a valid email
</div>
<div *ngIf="ctrl.errors?.required">
Please provide an email address
</div>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
ctrl = new FormControl(null, Validators.compose([Validators.email, Validators.required]));
}
评论中的讨论证明,这个具体问题的答案是:
<div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('email')">Provide a valid email.</div>
<div class="alert alert-danger" *ngIf="loginFormGroup.controls['email'].hasError('required')">Please provide an email address</div>
答案 1 :(得分:0)
您可以使用它来显示错误消息
<div *ngIf="loginFormGroup.get('email').touched && loginFormGroup.get('email').hasError('required')">Please provide an email address</div>
<div *ngIf="loginFormGroup.get('email').touched && loginFormGroup.get('email').hasError('email')">Provided email is not a valid email</div>