I'm trying to create a directive for an input element that will dynamically create an ng-pattern to check for a valid IP address in the input field. All of my attempts to do so have been completely unsuccessful. While I can dynamically modify other attributes, I can't create an ng-pattern that will affect the $valid status.
Here's the code that I've been working on which seems like it should work, but it doesn't do anything to the ng-pattern.
app.directive('ipAddress', function($parse) {
return {
link: function(scope, element, attrs) {
var model = $parse(attrs.ngPattern);
model.assign(scope, "/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/");
scope.$apply();
};
});
Directive:
<input ng-model="ip" ip-address required type="text" id="inputIP" placeholder="xxx.xxx.xxx.xxx">
Yes, I know I can just specify the ng-pattern inline with the <input> tag but the point is that I want to be able to do this dynamically in the code, and I'd like to keep the <input> tag cleaner by not embedding a bunch of regex code there.
Can anyone please help me? Thanks!