【问题标题】:validation error for forms not showing up properly in Angular5表单在 Angular5 中未正确显示的验证错误
【发布时间】:2019-01-14 13:46:52
【问题描述】:

每当我在城市输入框中输入内容时,它会在 HTML 上显示 errorMessage,但如果城市正确,它可以让我保存表单(即根据正则表达式测试没有数字、特殊字符)。问题是错误消息不断出现在 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>

【问题讨论】:

    标签: angular typescript angular5 angular4-forms


    【解决方案1】:

    在 Typescript 文件的第 6 行中,您传递的是对象而不是字符串。也许应该是:

    if (regEx.test(this.mailingAddress.city.value))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 2016-07-05
      • 2016-04-24
      • 2012-04-05
      • 2018-04-19
      • 2014-02-20
      • 1970-01-01
      相关资源
      最近更新 更多