Search code examples
javascriptangularjsangularjs-serviceng-pattern

Getting ng-patten as a variable from a service


Hello I am running an app wich needs a lot of form validation across pages, so I am trying to get validation patterns from a service i am using amongst the controllers.

The problem here is the ng-pattern isn't reacting the right way when I enter a correct email address.

This is a plunker and here's the code for the form

    <form method="POST" action="#" name="newsletterForm" id="newsletterForm" ng-controller="newsletterForm" novalidate>
        <input ng-pattern="/{{patterns.email}}/" type="email" name="email" ng-model="email" required />
        <button type="submit">Invia</button>
        {{newsletterForm.email.$error.pattern}}
    </form>

This is the app.js code

var app = angular.module('plunker', []);
app.controller('MainCtrl', function(){});
app.service('validationPatterns', function() {
    this.getPatterns = function() {
        return {
            email:  "^([a-zA-Z0-9\'\.\-\_]{2,64})([\@]{1})([a-zA-Z0-9\.\-\_]{2,64})([\.]{1})([a-zA-Z]{2,16})$"
        }
    }
});
app.controller('newsletterForm', function($scope, validationPatterns){
    $scope.patterns = validationPatterns.getPatterns();
});

I assume the problem might be that when angular renders the pattern inside the input tag it renders it escaping the backslashes

^([a-zA-Z0-9'.-_]{2,64})([@]{1})([a-zA-Z0-9.-_]{2,64})([.]{1})([a-zA-Z]{2,16})$

I have already tried adding the double backslashes in the service to make angular render it correctly but it's still not working. Any ideas?


Solution

  • ng-pattern works with a $scope variable. In your case it should be

    <input ng-pattern="patterns.email" 
    

    Updated plunker