Josh Josh - 1 year ago 95
Javascript Question

Angular ng-pattern regex validation using scope data

I'm pretty new at Angular, so forgive me if I'm asking or looking at this the wrong way, but I'm trying to dynamically build a form from fields in a database. When the page loads, I'm pulling data from the database and assigning those values to the scope in the Controller. In the HTML, I'm looping through those scope values to populate the page. In this example,

, and

<div ng-if="fields.field.dataType.type=='text'" class="form-group control-group" ng-class="{true: 'error'}[submitted && fieldsForm.$invalid]">
<div ng-repeat="fields in selectedPage.fieldValue">
<ng-form name="fieldsForm>
/*other code*/
<div class="controls"
<input type="{{fields.field.dataType.type}}"
ng-pattern="{{fields.field.regEx}}" />
<span class="help-label" ng-show="submitted && fieldsForm.$error.pattern">Please enter a valid field</span>
/*rest of code*/

The other parameters within the input tag work perfectly, but the regex field always returns invalid. I can substitute
and the validation works as expected.

Is there something different I have to do to pull in this regular expression from
? Why would the validation work when I hard-code
but fail when it's pulling from
even though they contain the same data?

Any insight would be appreciated, thanks!

Answer Source

NgPattern expect it's value to be a Regex parseable expression.

According to angularjs ngPattern docs:

  • If the expression evaluates to a RegExp object, then this is used directly.
  • If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters. For
    instance, "abc" will be converted to new RegExp('^abc$').

In your case, the regex is being parsed like a string, so the problem is with the scaping of the back slash inside the string "/^\d{11}$/". So, to fix it, you mustn't surround your regex with /, because it's not a regex, it's a string with the pattern for a regex, and you must escape your regex pattern as well (if it isn't being scaped yet), like so: "^\\d{11}$".

Also, you don't need to use {{}} since your regex string comes from an object on scope you can use it like this: ng-pattern="fields.field.regEx".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download