New email form input validator directive

When handling email inputs in Angular you usually want to validate the format of input before doing anything else with it. This validation could be handled in several ways but one of the most common was simply adding a regular expression match to the input with the pattern directive:

<form #form="ngForm">
<input type="email"
ngModel
name="email"
required
pattern="^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$">
<button [disabled]="!form.valid">Submit</button>
</form>

This approach works, but obviously, introduces a very ugly regular expression right into the middle of our template. If we had many different instances of email input fields in our application, we would quickly find ourselves duplicating this regular expression in multiple places as well. Thankfully, Angular 4 introduced a simple built-in email directive that does the same thing:

<form #form="ngForm">
<input type="email"
ngModel
name="email"
required
email>
<button [disabled]="!form.valid">Submit</button>
<p>Form State: {{form.valid ? "Valid" : "INVALID"}}</p>
</form>

This provides a much cleaner and more elegant way of validating simple email address inputs in Angular.

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

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