Let's follow the steps below to to add validations to the input fields of our blog post modal:
- First, we will need to provide a local property for our ngModel reference on our input. We can also add required, minlength, and maxlength properties to our input for validation:
<div class="form-group">
<label for="formTitleInput" class="form-control-label">Title</label>
<input type="text" class="form-control" id="formTitleInput"
placeholder="New Blog Post Title" name="title"
[(ngModel)]="model.title" #title="ngModel" required
minlength="5" maxlength="140">
</div>
- Having validation errors without any sort of user feedback isn't very helpful, so we'll add some conditional error classes to our input using the ngClass directive on our form-group and form-control classes:
<div class="form-group" [ngClass]="{'has-danger': title.invalid}">
<label for="formTitleInput" class="form-control-label">Title</label>
<input type="text" class="form-control"
[ngClass]="{'form-control-danger': title.invalid}" id="formTitleInput"
placeholder="New Blog Post Title" name="title"
[(ngModel)]="model.title" #title="ngModel" required
minlength="5" maxlength="140">
</div>
- Finally, we should add some instructions for the user, first as a subtle instruction and then as a more severe warning when the title field is invalid. We'll put both of these as new elements underneath our input:
<div class="form-group" [ngClass]="{'has-danger': title.invalid}">
<label for="formTitleInput" class="form-control-label">Title</label>
<input type="text" class="form-control"
[ngClass]="{'form-control-danger': title.invalid}" id="formTitleInput"
placeholder="New Blog Post Title" name="title"
[(ngModel)]="model.title" #title="ngModel" required
minlength="5" maxlength="140">
<div [hidden]="title.valid" class="form-control-feedback">
Sorry, name is required & has a minimum of 5 characters
</div>
<small class="form-text text-muted">
Title must be between 5 & 140 characters
</small>
</div>
- Now, when the user views the modal, they will see the basic instructions for how to title their blog post. If they attempt to input a value shorter than five characters, they will see an additional error display, and the entire field will be highlighted. If they attempt to input a value longer than 140 characters, the title field will simply not allow any more characters.