Angular 2表单验证,minLength验证器不起作用

前端之家收集整理的这篇文章主要介绍了Angular 2表单验证,minLength验证器不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下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.minLength(6)])]
        });
    }

}

在这种形式下,电子邮件字段对两个验证器都正常工作,即当我不输入任何内容时,它会给出“需要电子邮件”的消息,当我开始输入内容时,它会给出“需要下划线”的消息,当我输入“_”时所有错误消息都消失了.但是,当我尝试在密码字段上应用这样的2个验证器时,它不起作用.当我不输入密码时,它会显示“需要密码”的消息.但是当我键入少于6个字符的内容时,minLength消息根本不会出现.这段代码有什么问题?

error key is minlength而不是minLength:
<div *ngIf = "password.hasError('minlength') && !password.hasError('required')" class = "alert alert-danger">
  <span>Password should contain 6 characters</span>
</div>
原文链接:https://www.f2er.com/angularjs/143950.html

猜你在找的Angularjs相关文章