Developer
Developer

Reputation: 289

validation error for forms not showing up properly in Angular5

Whenever I type something in city input box it shows errorMessage on HTML but it let me save the form if city is correct(i.e as per regex test no numbers, special characters). The issue is error message keep on coming on HTML side regardless of city is correct or not. Its like on keypress it will show error message always.

Below is my ts method

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;
  }

Below is my HTML file

 <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>

Upvotes: 1

Views: 44

Answers (1)

Boudi
Boudi

Reputation: 132

In line 6 on your Typescript file you're passing an object instead of a String. Maybe it should be:

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

Upvotes: 1

Related Questions