1
votes

I am learning Angular 2 and is implementing a simple registration form with some basic validations. I have a input field with 3 validations; required, minLength and maxLenth Now for each of these validations, I want to show different validation message, i.e., for required: 'Name field is required' minLength: 'Name should be min 5 characters', etc

currently, as per the examples I found on Internet, I can see everyone implementing only one generic message by simply checking if the state is valid and then displaying one generic message for all validations errors.

How can I differentiate between different types of errors, so I can display different message for different errors?

Below is my code,

This works for single generic error message,

      <div class="divTableRow">
        <div class="divTableCell">First Name</div>
        <div class="divTableCell"><input type="text" id="txtFName" placeholder="First Name" [formControl]="registerUserForm.controls['txtFName']"></div>
        <div class="alert alert-danger" *ngIf="!registerUserForm.controls['txtFName'].valid">You must select a first name.</div>
      </div>

This doesn't work, if I try to differentiate between different type of message,

      <div class="divTableRow" >
        <div class="divTableCell">First Name</div>
        <div class="divTableCell"><input type="text" id="txtFName" placeholder="First Name" [formControl]="registerUserForm.controls['txtFName']"></div>
        <div class="alert alert-danger" *ngIf="registerUserForm.controls['txtFName'].error.required && !registerUserForm.controls['txtFName'].valid">You must select a first name.</div>
        <div class="alert alert-danger" *ngIf="registerUserForm.controls['txtFName'].error.minLength && !registerUserForm.controls['txtFName'].valid">You must enter atleast 5 characters.</div>
      </div>

In TS file, I have

'txtFName': [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(50)])],

Basically, here in the HTML, the statement !registerUserForm.controls['txtFName'].valid will only provide if the control is valid or invalid, but don't provide information about which rule failed. I want to somehow identify the type of error.

1

1 Answers

2
votes

This should work:

<small *ngIf="registerUserForm.controls['txtFName'].hasError('required')">Name is required!</small>
<small *ngIf="registerUserForm.controls['txtFName'].hasError('minlength')">Name has to be at least 5 chars</small>
<small *ngIf="registerUserForm.controls['txtFName'].hasError('maxlength')">Name can be max 50 chars</small>

Demo Plunker

You could also make use of valueChanges:

this.registerUserForm.get('txtFName').valueChanges
.subscribe(data => {
  console.log('changes happened. Do something!')
  }
})