Angular 5 表单验证(必需)无效
Angular 5 form validation (required) not working
我正在学习 Angular 5 使用 TypeScript。我对它完全陌生。我现在正在尝试构建一个表单并对其进行验证。但是它不能正常工作。
这是我的组件:
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
animations: [routerTransition()]
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
errors = [];
constructor(private fb: FormBuilder, public router: Router, private globals: GlobalsService, private http: Http) {
}
ngOnInit() {
this.loginForm = new FormGroup({
email: new FormControl("", Validators.required),
password: new FormControl("")
});
}
onLoggedin(formData) {
alert("Submit form");
}
}
如您所见,我在电子邮件字段上设置了“必需”验证属性。
这是我的 html.
<div class="login-page" [@routerTransition]>
<div class="row justify-content-md-center">
<div class="col-md-4">
<img src="assets/images/logo.png" width="150px" class="user-avatar" />
<h1>Yo Cash Flow</h1>
<div class="alert alert-danger" *ngFor="let error of errors">
<strong>{{ error.msg }}</strong>
</div>
<form [formGroup]="loginForm" role="form" (ngSubmit)="onLoggedin(loginForm.value)">
<div class="form-content">
<div class="form-group">
<input type="text" name="email" formControlName="email" class="form-control input-underline input-lg" placeholder="Email">
<div *ngIf="loginForm.controls['email'].errors.required" class="text-danger">Email is required</div>
</div>
</div>
<button type="submit" class="btn rounded-btn"> Log in </button>
<a class="btn rounded-btn" [routerLink]="['/signup']">Sign up</a>
</form>
</div>
</div>
</div>
如您所见,我正在尝试单独显示错误。我的意思是对于“必需”属性,我正在检索这样的错误消息 errors.required。但它不起作用。但是当我尝试像下面这样使用“有效”时,它正在工作。
loginForm.controls['email'].invalid
但我想单独检索错误,因为我想针对不同的错误显示不同的消息。我怎样才能解决这个问题?为什么当我使用 loginForm.controls["email"].errors.required
时它不起作用?针对不同的验证规则显示不同消息的正确方法是什么?
您可以使用 errors
属性,像这样:
loginForm.controls['email'].errors
如果没有错误,它将 return 为 null,否则它将 return 一个像这样的对象:
{ required : true }
然后您只需要创建一个函数来 return 人类可读的错误消息,如下所示:
getErrorMessage(controlName, displayName) {
let result = "";
let errors = loginForm.controls[controlName].errors;
if (errors.required) {
result += (displayName + " is required.");
}
if (errors.whatever) {
result += "Whatever you like";
}
return result;
}
您必须在按钮的 *ngIf
或 [disabled] 属性 内使用 (loginForm.valid)
。这会自动检查表单是否通过 ts 文件验证。
此外,在 ts 文件中,您可以编写验证:
new FormControl('',[Validators.required])
像这样。
我刚刚花了几个小时尝试在我的项目中调试这个问题,我的问题原来是使用:
<input type="checkbox" formControlName="testing" />
而不是:
<input type="checkbox" [formControl]="form.controls['testing']" />
在我的例子中,FormControl "testing" 是使用 form.AddControl() 动态添加的 - 执行名称绑定的第二种方法也将模型绑定到输入。
希望这可以帮助解决这个问题的人!
在 Angular 文档中存在两种验证表单的方法,请尝试使用“正确”的方法来获得预期结果:
- Template-driven forms - 在简单形式下效果更好(静态验证器)
- Reactive Forms - 当您需要动态转换验证器时效果更好(更复杂的形式)
我建议学习Reactive Forms(Template-driven template-driven template-driven template-driven easy to learn it)
反应形式:
- HTML:
<form [formGroup]="loginForm" (ngSubmit)="onLoggedin(loginForm.value)">
<div>
<input type="text" name="email" formControlName="email" placeholder="Email"/>
<div *ngIf="email.errors?.required && email.touched">Email is required</div>
<div *ngIf="email.errors?.pattern && email.touched">Invalid Pattern</div>
</div>
<div>
<button type="submit"[disabled]="!loginForm.valid">Login</button>
</div>
</form>
- TS
export class AppComponent implements OnInit {
loginForm: FormGroup;
errors = [];
email: FormControl = new FormControl('', [
Validators.required,
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$'),
]);
password: FormControl = new FormControl('');
ngOnInit() {
this.loginForm = new FormGroup({
email: this.email,
password: this.password,
});
}
onLoggedin(formData) {
alert('Submit form');
}
备注:
我在组件的根部声明 FormControls 以直接绑定到 html 文件中;
在验证器消息“email.errors?.required”中我使用 ?允许“email.errors”(当电子邮件有效时)为空且不抛出错误;
我正在学习 Angular 5 使用 TypeScript。我对它完全陌生。我现在正在尝试构建一个表单并对其进行验证。但是它不能正常工作。
这是我的组件:
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
animations: [routerTransition()]
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
errors = [];
constructor(private fb: FormBuilder, public router: Router, private globals: GlobalsService, private http: Http) {
}
ngOnInit() {
this.loginForm = new FormGroup({
email: new FormControl("", Validators.required),
password: new FormControl("")
});
}
onLoggedin(formData) {
alert("Submit form");
}
}
如您所见,我在电子邮件字段上设置了“必需”验证属性。 这是我的 html.
<div class="login-page" [@routerTransition]>
<div class="row justify-content-md-center">
<div class="col-md-4">
<img src="assets/images/logo.png" width="150px" class="user-avatar" />
<h1>Yo Cash Flow</h1>
<div class="alert alert-danger" *ngFor="let error of errors">
<strong>{{ error.msg }}</strong>
</div>
<form [formGroup]="loginForm" role="form" (ngSubmit)="onLoggedin(loginForm.value)">
<div class="form-content">
<div class="form-group">
<input type="text" name="email" formControlName="email" class="form-control input-underline input-lg" placeholder="Email">
<div *ngIf="loginForm.controls['email'].errors.required" class="text-danger">Email is required</div>
</div>
</div>
<button type="submit" class="btn rounded-btn"> Log in </button>
<a class="btn rounded-btn" [routerLink]="['/signup']">Sign up</a>
</form>
</div>
</div>
</div>
如您所见,我正在尝试单独显示错误。我的意思是对于“必需”属性,我正在检索这样的错误消息 errors.required。但它不起作用。但是当我尝试像下面这样使用“有效”时,它正在工作。
loginForm.controls['email'].invalid
但我想单独检索错误,因为我想针对不同的错误显示不同的消息。我怎样才能解决这个问题?为什么当我使用 loginForm.controls["email"].errors.required
时它不起作用?针对不同的验证规则显示不同消息的正确方法是什么?
您可以使用 errors
属性,像这样:
loginForm.controls['email'].errors
如果没有错误,它将 return 为 null,否则它将 return 一个像这样的对象:
{ required : true }
然后您只需要创建一个函数来 return 人类可读的错误消息,如下所示:
getErrorMessage(controlName, displayName) {
let result = "";
let errors = loginForm.controls[controlName].errors;
if (errors.required) {
result += (displayName + " is required.");
}
if (errors.whatever) {
result += "Whatever you like";
}
return result;
}
您必须在按钮的 *ngIf
或 [disabled] 属性 内使用 (loginForm.valid)
。这会自动检查表单是否通过 ts 文件验证。
此外,在 ts 文件中,您可以编写验证:
new FormControl('',[Validators.required])
像这样。
我刚刚花了几个小时尝试在我的项目中调试这个问题,我的问题原来是使用:
<input type="checkbox" formControlName="testing" />
而不是:
<input type="checkbox" [formControl]="form.controls['testing']" />
在我的例子中,FormControl "testing" 是使用 form.AddControl() 动态添加的 - 执行名称绑定的第二种方法也将模型绑定到输入。
希望这可以帮助解决这个问题的人!
在 Angular 文档中存在两种验证表单的方法,请尝试使用“正确”的方法来获得预期结果:
- Template-driven forms - 在简单形式下效果更好(静态验证器)
- Reactive Forms - 当您需要动态转换验证器时效果更好(更复杂的形式)
我建议学习Reactive Forms(Template-driven template-driven template-driven template-driven easy to learn it)
反应形式:
- HTML:
<form [formGroup]="loginForm" (ngSubmit)="onLoggedin(loginForm.value)">
<div>
<input type="text" name="email" formControlName="email" placeholder="Email"/>
<div *ngIf="email.errors?.required && email.touched">Email is required</div>
<div *ngIf="email.errors?.pattern && email.touched">Invalid Pattern</div>
</div>
<div>
<button type="submit"[disabled]="!loginForm.valid">Login</button>
</div>
</form>
- TS
export class AppComponent implements OnInit {
loginForm: FormGroup;
errors = [];
email: FormControl = new FormControl('', [
Validators.required,
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$'),
]);
password: FormControl = new FormControl('');
ngOnInit() {
this.loginForm = new FormGroup({
email: this.email,
password: this.password,
});
}
onLoggedin(formData) {
alert('Submit form');
}
备注:
我在组件的根部声明 FormControls 以直接绑定到 html 文件中;
在验证器消息“email.errors?.required”中我使用 ?允许“email.errors”(当电子邮件有效时)为空且不抛出错误;