Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between html input pattern and angular ngPattern?

Tags:

angularjs

I notice some developers are using html input pattern for validation in an angular styled form:

<input id="email" name="email"
    type="text"
    ng-model="vm.contact.mail"
    pattern="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
    required />

<span ng-show="!vm.contact.email.$error.required && 
    vm.contact.email.$error.pattern && 
    vm.contact.email.$dirty">
    Email is not in the correct format.</span>

It appears to work the same with

ng-pattern="/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/"

Are those two ways indeed interchangeable? Is there any advantage/preference for one over the other in the usage or performance?

like image 678
Blaise Avatar asked Feb 12 '23 02:02

Blaise


1 Answers

Form validation

Both options will trigger form validation, since ng-pattern is just converted to pattern (tested).

Difference

There is just a slight difference between ng-pattern and pattern. According to the documentation ng-pattern also allows you to pass Regexp expressions defined in your scope. Also, ng-pattern will not trigger default browser validation (red border, error message around input).

So you can decide whenever you want to have default browser validation in your application or not.

Example plunker showing both in action.

like image 130
Himmet Avsar Avatar answered May 08 '23 11:05

Himmet Avsar