Displaying appropriate validation messages
Now, the input needs to have a value; otherwise, the validation fails. But, how can we know if the validation has failed? ngModel comes to our rescue here. It can provide the validation state of the particular input. And that gives us what we need to display an appropriate validation message.
Let's go back to the input control for the Workout name. In order to get a validation message to display, we have to first modify the input tag to the following:
<input type="text" name="workoutName" #name="ngModel" class="form-control" id="workout-name" placeholder="Enter workout name. Must be unique." [(ngModel)]="workout.name" required>
We have added a local variable called #name and assigned ngModel to it. This is called a template reference variable and we can use it with the following label to display a validation message for the input:
<label *ngIf="name.control.hasError('required') && (name.touched)" class="alert alert-danger validation-message">Name is required</label>
We are showing the validation message in the event that the name is not provided and the control has been touched. To check the first condition, we retrieve the hasError property of the control and see if the error type is required. We check to see if the name input has been touched because we do not want the message to display when the form first loads for a new workout.
You will notice that we are using a somewhat more verbose style to identify validation errors than is required in this situation. Instead of name.control.hasError('required'), we could have used !name. valid and it would have worked perfectly fine. However, using the more verbose approach allows us to identify validation errors with greater specificity, which will be essential when we start adding multiple validators to our form controls. We'll look at using multiple validators a little later in this chapter. For consistency, we'll stick with the more verbose approach.
Load the new Workout page (/builder/workouts/new) now. Enter a value in the name input box and then delete it. The error label appears as shown in the following screenshot:
