The Tricky Part of Validation Attributes in Angular
In my free course on the Fundamentals of Angular, there are just over 2 hours of content on template-driven forms in Angular. One of the main parts of this is coverage of how to validate user input. This is an important part of any framework’s forms handling.
But in Angular, there’s a bit of an unmet promise when you learn about forms validation, and this can be confusing, so I’d like to just quickly cover the issue to help clear up any confusion you may encounter when doing forms validation in Angular.
When you first learn about forms validation, you quickly discover that there are several attributes you can add to an input control to validate that control. Angular’s integration with this validation is simple and effective. It’s a bit like magic.
Want to make sure that a field is required? Simply add the “required” attribute to the input element. Angular handles the rest for you. Want to make sure that a password has at least 8 characters? Use the minlength attribute. There’s maxlength as well. And if you really have a tough validation problem, then there’s the pattern attribute which uses regular expressions, and as they say, “now you have two problems” lol.
These attributes are part of the HTML5 spec, so using them is really natural. You’re just leveraging the built-in parts of HTML and Angular is just making them five times more awesome.
So after learning these four attributes you may think “awesome, what other HTML validation attributes are there that I can use? Some quick Googling (or Binging?) will lead you to several more of these same validation attributes. There’s min & max for dates & numbers, there’s a step somewhat more obtuse attribute, and of course there’s the good old type attribute on input elements. Such as type=”email” and then suddenly you discover the unmet tacit promise of Angular validation.
Because these attributes do nothing with Angular validation. Nada. Squat.
At first, you may think that you’re just not doing them right. But that’s not it. They’re not used by Angular. The framework simply doesn’t utilize them. If you want to mimic them, you have to create custom validators yourself.
Now there is logic behind all this but ultimately it doesn’t matter. You just need to know what is and is not supported. So here’s a summary of useful information when doing validation in Angular’s template-driven forms.
Supported Validation Attributes:
Unsupported Validation Attributes:
So don’t get confused if you run into this. It’s just the way it is.
Signup for my newsletter here.
Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @GoThinkster