Let’s look at how we can use the ngPattern directive to check answers in our quiz question.

Here’s my latest JSFiddle of the quiz:

If you look at the input element on the HTML tab, you should see the parameter: ng-pattern="word.text". This basically tells Angular that this input field needs to match a RegEx pattern to be valid. If the input field value doesn’t match, then it’s invalid and should return an error.

Further down the page, I’m using ngIf to display validation messages. Note that one of the messages has ng-if="myForm.myInput.$error.pattern". Since we’re using Angular to validate our form, if we add validation parameters in the field, Angular will flag any validation errors within an $error property on the fields.

For example, if we add a parameter ng-pattern="donut", then the field’s $error property will show {pattern:true}. If I type in “donut”, then the $error property won’t show anything for pattern, since the pattern would match.

Speaking of donuts, or doughnuts

What really makes ngPattern handy is that it converts to a RegExp. So if you have a spelling variation of a word, such as “donut” or “doughnut”, you can put ng-pattern="(donut|doughnut)" in your input field and both will validate. Unfortunately, when I was a kid, I failed a spelling bee when I misspelled “doughnut” as “donut”, even though I thought they wanted me to spell “donut”.

Anyway, there’s a few other directives I’m using too, such as ngMinlength, ngMaxlength, and ngRequired, that I wasn’t able to discuss yet, but plan on covering in later posts.

Share This
%d bloggers like this: