Adding validators

As a matter of fact, we already added a basic validator to the createForm():

[...]
Title: ['', Validators.required],
[...]

This will definitely make Angular aware of the fact that the quiz Form Model will never be valid as long as there's an empty Title, which is precisely what we want since Title is a required field.

Let's quickly test it out. Launch the project in debug mode, navigate through a quiz, click on the Edit button, and try to entirely remove the existing Title:

It works! It seems that we're unable to submit the form as long as the Title textbox is empty.

The only missing thing here is a visual warning of some sort, otherwise there's a high chance that the user won't understand what he has to do. We can easily fill the gap with the help of some neat Bootstrap classes; open the quiz-edit.component.html template file and update it with the following highlighted lines:

[...]

<div class="form-group"
[ngClass]="{ 'has-error has-feedback' : form.get('Title').errors?.required }">
<label for="title">Quiz title:</label>
<br />
<input type="text" id="title"
formControlName="Title" required
placeholder="choose a title..."
class="form-control"
/>
<span *ngIf="form.get('Title').errors?.required"
class="glyphicon glyphicon-remove form-control-feedback"
aria-hidden="true"></span>

<div *ngIf="(form.get('Title').dirty
|| form.get('Title').touched)
&& form.get('Title').errors?.required"
class="help-block">
Title is a required field: please insert a valid title.
</div>
</div>

[...]

Once done, if we repeat our previous test, we should see something like this:

We're definitely sending some relevant signals here; now we can be sure that our users will find out what to do.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.108.175