【发布时间】:2016-10-30 02:17:07
【问题描述】:
我有以下 Angular 2 形式:
<register>
<form [ngFormModel] = "registrationForm">
<div class = "form-group">
<label class = "control-label" for="email">Email</label>
<input class = "form-control" type="email" id="email" ngControl="email" #email="ngForm">
</div>
<div *ngIf = "email.touched && email.errors">
<div *ngIf = "!email.errors.required && email.errors.underscoreNotFound" class = "alert alert-danger">
<span>Underscore is required</span>
</div>
<div *ngIf = "email.errors.required" class = "alert alert-danger">
<span>Email is required</span>
</div>
</div>
<div class = "form-group">
<label class = "control-label" for="password">Password</label>
<input class = "form-control" type="password" id="password" ngControl="password" #password="ngForm">
</div>
<div *ngIf = "password.touched && password.errors">
<div *ngIf = "password.errors.minLength && !password.errors.required" class = "alert alert-danger">
<span>Password should contain 6 characters</span>
</div>
<div *ngIf = "password.errors.required" class = "alert alert-danger">
<span>Password is required</span>
</div>
</div>
</form>
</register>
这是我实现验证器的组件:
import {Component} from '@angular/core';
import {Control, ControlGroup, FormBuilder, Validators} from '@angular/common';
import {CustomValidator} from './CustomValidator';
@Component({
selector: 'register',
templateUrl: './app/authentication/register_validation/register.html',
})
export class RegisterComponent{
registrationForm: ControlGroup;
constructor(formBuilder:FormBuilder)
{
this.registrationForm = formBuilder.group({
email: ['',Validators.compose([Validators.required, CustomValidator.underscore])],
password: ['',Validators.compose([Validators.required,Validators.minLength(6)])]
});
}
}
在这种形式中,email 字段对于两个验证器都可以正常工作,即当我不输入任何内容时,它会给出 "Email is required" 消息,当我开始输入内容时,它会给出 "Underscore is required" 消息,当我输入 @987654328 时@所有错误信息消失。但是,当我尝试在 password 字段上应用这样的 2 个验证器时,它不起作用。当我不输入密码时,它会给出"Password is required" 的消息。但是当我输入少于 6 个字符的内容时,minLength 消息根本不会出现。这段代码有什么问题?
【问题讨论】:
-
你能用你的代码创建一个plnkr.co
-
另外,您使用的版本低于 RC3。已弃用。尝试新的 RC3 版本
-
可能会参考这个答案stackoverflow.com/a/38092249/5868331
-
@mayur 是的。我通过为 minLength 添加自定义类来解决问题,但我想使用原始验证器。无论如何谢谢:)
-
原始验证器表示默认角度 2 ????
标签: validation angular angular2-forms