gpt4 book ai didi

validation - Angular 2 表单验证,minLength 验证器不工作

转载 作者:太空狗 更新时间:2023-10-29 16:49:24 25 4
gpt4 key购买 nike

我有以下 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” 消息,当我键入 “_” 时,所有错误消息都会消失。但是,当我尝试在 password 字段上应用这样的 2 个验证器时,它不起作用。当我不输入密码时,它会显示消息 "Password is required"。但是当我键入少于 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>

关于validation - Angular 2 表单验证,minLength 验证器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38064592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com