每当我在城市输入框中键入内容时,都会在HTML上显示errorMessage,但如果城市正确(例如,根据regex测试没有数字,特殊字符),它可以让我保存表单。问题是无论城市正确与否,错误消息都会不断出现在HTML端。就像在按键上一样,它将始终显示错误消息。
下面是我的ts方法
validateCity() {
this.mailingAddress.city.error = false;
this.mailingAddress.city.errorMessage = '';
let hasErrors: boolean = false;
let regEx = new RegExp(/^[a-zA-Z]+(?:[\s-][a-zA-Z]+)*$/);
if (regEx.test(this.mailingAddress.city)) {
return false;
} else{
hasErrors = true;
this.mailingAddress.city.error = true;
this.mailingAddress.city.errorMessage = 'Invalid City';
}
return hasErrors;
}
下面是我的HTML文件
<div class="city-info-container row">
<div class="col-sm-6 pb-3 city-wrapper">
<label for="mailingCity" class="required">City</label>
<div class="input-wrapper">
<input type="text" [maxLength]="255" name="mailingCity" placeholder="Enter City" [disabled]="setAsResidential" [(ngModel)]="mailingAddress.city.value"
(keyup)="validateCity()" (blur)="validateCity()"
>
</div>
<!-- end .input-wrapper -->
<div class="clearfix"></div>
<p *ngIf="mailingAddress.city.error" class="clearfix error-message">
<i class="fa fa-exclamation-triangle" aria-hidden="true"></i> {{mailingAddress.city.errorMessage}}</p>
</div>
答案 0 :(得分:1)
在Typescript文件的第6行中,您传递的是对象而不是字符串。也许应该是:
if (regEx.test(this.mailingAddress.city.value))