gpt4 book ai didi

javascript - 如何在单击按钮时显示验证消息?

转载 作者:行者123 更新时间:2023-12-03 01:16:21 27 4
gpt4 key购买 nike

您能告诉我如何在单击按钮时显示验证消息吗?这是我的代码 https://stackblitz.com/edit/angular-ugdbvg?file=src/app/app.component.html

我想在用户按下提交按钮时显示必需错误消息。

  <form novalidate [formGroup]="searchForm" class="calform">
<section class="col-sm-6 bg-white pl-20 pr-20">

<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">name<span class="color-red fontWt">&nbsp;*</span></label>
<input type="text" placeholder="Enter name" formControlName="name">
<p class="message" [hidden]="searchForm.get('name')">Required</p>
</div>

<div class="form-group col-sm-4 pl-0 error">
<label class="field-title mb-5">last name <span class="color-red fontWt">&nbsp;*</span></label>
<input type="text" placeholder="Enter last name" formControlName="lastName">
<p class="message" [hidden]="searchForm.get('lastName')">Required</p>
</div>
<button (click)="submitHandler()">submit</button>
</section>
</form>

js

this.searchForm = this.fb.group({
name: ['', Validators.required],
lastName: ['', Validators.required]

});

最佳答案

添加以下行进行检查:

<span class="error" *ngIf="!!searchForm.controls.name.errors.required && (!!searchForm.controls.name.dirty || !!searchForm.controls.name.touched)">
Name is required.
</span>
<span class="error" *ngIf="!!searchForm.controls.lastName.errors.required && (!!searchForm.controls.lastName.dirty || !!searchForm.controls.name.touched)">
lastName is required.
</span>

在你的 ts 文件中:

submitHandler() {
if(this.searchForm.valid) {
// Logic
}
}

https://stackblitz.com/edit/angular-utvw23

关于javascript - 如何在单击按钮时显示验证消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51999566/

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