gpt4 book ai didi

javascript - Angular 禁用按钮和垫输入错误消息

转载 作者:太空狗 更新时间:2023-10-29 18:22:20 24 4
gpt4 key购买 nike

我有一个文本框和一个按钮。文本框输入是一个 url,并且有一个验证 url 格式的方法,在这个例子中是 isUrlFormatValid()

如果 isUrlFormatValid() 失败,则文本框下方会出现一条错误消息,并且按钮变为被动状态,无法点击。但我的问题是,当页面首次加载时,此方法结果自动为 false,因此对于空框也会直接显示错误消息。

<mat-card class="">
<mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayoutGap="15px">

<div>
<mat-form-field>
<mat-label>Enter link here</mat-label>
<input type="url" matInput [(ngModel)]="domainName">
</mat-form-field>
<mat-error *ngIf="isUrlFormatValid()">
Please enter the link in correct format
</mat-error>
</div>

</mat-card-content>
<div>
<button type="button" id="search" class="" [disabled]="isUrlFormatValid()"
(click)="addClicked()">Add Domain
</button>
</div>
</mat-card>

而ts文件中的方法定义是:

isUrlFormatValid() {
const pattern = /^((((https?)(:\/\/))?((www)\.)?)?|mailto:(\w+\.?\w+)\@)([a-z0-9]+\.[a-z0-9]+)+$/;

if (pattern.test(this.domainName)) {
return false;
}
return true;
}

如果我更改 ts 文件中的行:

if (pattern.test(this.domainName))

到:

if (pattern.test(this.domainName) || this.domainName == null) 

然后错误消息问题就解决了,但是这次按钮在启动时是可点击的,如果我写了一些是的,它正在工作,但是当页面首次加载时它会变为事件状态。

那么我该如何解决这个问题呢?

最佳答案

You may achieve the same without using an extra function. Just use some template driven form attributes & its control states as mentioned below. Also, It is a good practice to enclose your form elements in a <form> tag. So, if you use form, your scenario would be -

只需将其添加到您的组件类 -

public pattern = /^((((https?)(:\/\/))?((www)\.)?)?|mailto:(\w+\.?\w+)\@)([a-z0-9]+\.[a-z0-9]+)+$/;

而您的 HTML 将是 -

<form #f="ngForm" (ngSubmit)="addClicked()">
<mat-card class="">
<mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayoutGap="15px">
<div>
<mat-form-field>
<mat-label>Enter link here</mat-label>
<input type="url" matInput [(ngModel)]="domainName" #url="ngModel" [class.is-invalid]="url.invalid && url.touched"
name="url" [pattern]="pattern" required>
</mat-form-field>
<mat-error *ngIf="url.invalid && (url.dirty || url.touched)">
Please enter the link in correct format
</mat-error>
</div>
</mat-card-content>
<div>
<button type="button" id="search" class="" [disabled]="!f.valid">Add
Domain
</button>
</div>
</mat-card>
</form>

关于javascript - Angular 禁用按钮和垫输入错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53816469/

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