Improving the form 

So far, we have covered the basic mechanisms for knowing when a form is erroneous and how to display a text based on a specific error. Let's build on that knowledge by covering some more examples. First off, we will add more validation types to our input field:

<input minlength="3" required #name="ngModel" name="name">
{{ name.errors | json }}

Now we have added minlength as a validation rule to our element, besides the pre-existing required rule. Required is the prioritized error, so that will show first. If we input some characters then the required error goes away. It should now display the following:

{"minlength": { "requiredLength": 3, "actualLength": 1 }  }

Just like with the required error, we can show an error text for just this error, like so:

<div *ngIf="name.errors && name.errors.minlength" >
Name value is too short
</div>

There are some validation rules already written for us:

  • required, which requires the value to be non empty
  • requiredTrue, which specifically requires the value to be true
  • minlength, which says the value needs to have a certain minimum length
  • maxlength, which says the value cannot be over a certain length
  • pattern, which forces the value to adhere to a RegEx pattern
  • nullValidator, which checks the value is not null
  • compose, which is used if you want to compose multiple validators into one, the validation rule is the result of taking the union of all validators provided

Try to see if any of those covers your scenario. You might find that some validation rules are missing. If that is the case, then this can be remedied by creating a custom validator. We will cover how to build a custom validator rule later in this chapter.

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

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