For some reason the initialized value doesn't appear in the field, but the second field without the ng-pattern does work. any ideas?
angular.module('app', []).controller('MainCtrl', function($scope) {
$scope.widget = {title: 'abc', title2: 'abc'};
});
<div ng-app="app" ng-controller="MainCtrl">
<input ng-model="widget.title" required ng-pattern="/[a-zA-Z]{4}[0-9]{6,6}[a-zA-Z0-9]{3}/">
<br /><br />
input 1: {{ widget.title }}
<br /><br />
<input ng-model="widget.title2" required>
<br /><br />
input 2: {{ widget.title2 }}
</div>
Here is the Fiddle http://jsfiddle.net/wkzab/1/
The ng-pattern Directive in AngularJS is used to add up pattern (regex pattern) validator to ngModel on input HTML element. It is used to set the pattern validation error key if input field data does not match a RegExp that is found by evaluating the Angular expression specified in the ngpattern attribute value.
"ng" stands for Next Generation, as Angular is the next generation of HTML .
AngularJS ng-required Directive The ng-required directive sets the required attribute of a form field (input or textarea). The form field will be required if the expression inside the ng-required attribute returns true. The ng-required directive is necessary to be able to shift the value between true and false .
I too was facing same problem. Found a workaround to do this.
You have to do something like this in your controller.
$scope.myRegex = /[a-zA-Z]{4}[0-9]{6,6}[a-zA-Z0-9]{3}/;
(don't put expression in quotes)
Finally
<input ng-model="widget.title" required ng-pattern="myRegex">
It will now be working.
UPDATE
I looked into it a bit (never really used Angular), and by using the name
attribute on the form and inputs, you can grab an error like shown in my newest JSFiddle. Its in the format: {{formName.inputName.$error}}
. This returns an object with parameters that equal a boolean. So {{form.title.$error.pattern}}
will be true
when there is an error with the regular expression (so you would display the error). I also cleaned (works the same) your regex to: /^[A-Z]{4}\d{6}[A-Z\d]{3}$/i
.
OLD
The ng-pattern
attribute attempts to match the field based on this regular expression: /[a-zA-Z]{4}[0-9]{6,6}[a-zA-Z0-9]{3}/
. This translates to 4 alphabetical characters, 6 digits, and 3 alphanumeric characters. Once you have a matching pattern, it will show up.
You should be able to remove the ng-pattern
attribute or change the expression to be less specific. For example, this JSFiddle will accept any value as long as the entire string is alphanumeric. Update the question if you want help with a different pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With