Building  Large-Scale Web Applications with Angular
上QQ阅读APP看书,第一时间看更新

Managing multiple validation messages

You'll see that the conditions for displaying the message now test for the length not being zero. This prevents the message from displaying in the event that the control is touched but left empty. In that case, the title required message should display. This message only displays if nothing is entered in the field and we accomplish this by checking explicitly to see if the control's hasError type is required:

<label *ngIf="title.control.hasError('required')" class="alert alert-danger validation-message">Title is required.</label>

Since we are attaching two validators to this input field, we can consolidate the check for the input being touched by wrapping both validators in a div tag that checks for that condition being met:

<div *ngIf="title.touched"> 
  . . . [the two validators] . . . 
</div> 

What we just did shows how we can attach multiple validations to a single input control and also display the appropriate message in the event that one of the validation conditions is not met. However, it's pretty clear that this approach will not scale for more complicated scenarios. Some inputs contain a lot of validations and controlling when a validation message shows up can become complex. As the expressions for handling the various displays get more complicated, we may want to refactor and move them into a custom directive. Creating a custom directive will be covered in detail in Chapter 4, Angular Directives in Depth.