我有以下角2形式:角2表單驗證的minLength驗證工作不
<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"
消息,當我鍵入"_"
時,所有錯誤消息都會消失。但是,當我嘗試在password
字段上應用這兩個驗證器時,它不起作用。當我不輸入密碼時,它會給出消息"Password is required"
。但是,當我鍵入少於6個字符的東西時,根本沒有出現minLength
消息。這段代碼有什麼問題?
你可以用你的代碼創建一個https://plnkr.co –
你也使用較低版本,然後是RC3。這已被棄用。嘗試新的RC3版本 –
可能會參考此答案http://stackoverflow.com/a/38092249/5868331 – mayur