gpt4 book ai didi

Angular 2 : Validate form without defining error messages at each input?

转载 作者:太空狗 更新时间:2023-10-29 17:20:41 26 4
gpt4 key购买 nike

我想要 angular2 中的验证表单。我学习了一些文档,它会这样定义:

<form [ngFormModel]="form">
<input type="text" ngControl="username" />

<p *ngIf="username.pending">Fetching data from the server...</p>

<div *ngIf="username.dirty && !username.valid && !username.pending">
<p *ngIf="username.errors.required">Username is required.</p>
<p *ngIf="username.errors.startsWithNumber">Your username can't start with a number</p>
<p *ngIf="username.errors.usernameTaken">This username is taken</p>
</div>

<button (click)="submitData()" [disabled]="!form.valid" class="btn btn-primary">Sumbit data</button>
</form>
constructor(private builder: FormBuilder) {

this.username = new Control(
"",
Validators.compose([Validators.required, UsernameValidator.startsWithNumber]),
UsernameValidator.usernameTaken
);

this.form = builder.group({
username: this.username
});
}

对于每个输入,我都需要定义许多错误消息。我觉得不好。
我想要像 jquery.validate,我只是定义 input 并且错误消息将自动呈现,就像这样

<input required name="username" maxlength='8' pattern="^(?!\s|.*\s$).*$" ...> 

最佳答案

要减少代码,一种方法是编写一个组件。

它将处理所有的条件检查错误消息

This guy did a nice job here of implementing and explaining it.


带有组件的 HTML 看起来像这样

<input ngControl="email" id="email" />
<control-messages control="email"></control-messages>

所有的肮脏的工作都将进入control-messages组件。

关于 Angular 2 : Validate form without defining error messages at each input?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36145844/

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