Often, when taking user input, we need to validate that the user is entering data in a certain format. When taking email addresses, for example, you want to make sure what they enter matches the format of an email address (ex. firstname.lastname@example.org). Anytime, as a developer, you come across a situation where you need to enforce pattern matching, Regex (Regular Expression) should be the first thing that comes to mind.
I’ll post the link to the code pen, and then explain.
Go ahead and have a look. The HTML for this example should be pretty straightforward. The key is the use of the ng-pattern directive. It’s worth it to note that there exists a ‘pattern’ tag in regular HTML that allows us to enter a pattern directly and accomplish the same validation. However, ng-pattern (as with other Angular directives) allows us to define the pattern in the controller (with a variable on the $scope) as well as directly in the HTML. Here to show that ng-pattern can do both, we’ve got two different inputs, one defines the pattern directly and the other uses a variable in the controller.
The pattern that I’ve defined allows the user to enter uppercase and lowercase letters as well as numbers. Patterns can get immensely more complex, but for our purposes, I think this example suffices. If you have any experience with Angular, this should have been really easy to follow. If you were like me, and originally just didn’t know the ng-pattern existed, then hopefully this helped!
If you suggestions on specifics aspects of Regex that are trickier and you would like to see a post on, let me know!! @jamesqquick