Xinrui Ma
Xinrui Ma

Reputation: 2105

regex doesn't work with data binding

I am doing validation with Angular,

<div ng-if="field.required !== 'true'">
   <input id="fld-{{field.id}}" name="{{field.id}}" ng-model="$ctrl.configuration[$ctrl.selectedPlatform][field.id]" ng-pattern="{{field.regex}}">
</div>

This is the field data:

{
  "id": "addItemToHistoryAfterNSeconds",
  "label": "Add Video to History after how many seconds?",
  "type": "string",
  "default": "5",
  "regex": "/^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$/"
}

So this basically matches numeric value, for testing purpose.

However, the validation doesn't pass, shows ng-invalid.

When I write ng-patter="/^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$/" directly, the validation pass.

Anyone knows why?

Update:

I want to valid only numeric value, so I will be using:

/^[+]?([0-9]+(?:[\\.][0-9]*)?|\\.[0-9]+)$/

Upvotes: 1

Views: 413

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

There is a difference between how regex is defined in the HTML and JS code. If ng-pattern allows you to use "/regex-here/" notation with single backslashes denoting literal backslashes, JS code does not as you define strings there using C strings (that is, string literals where you may use escape sequences).

There, you may use either a constructor initialization (using a string), or a regex literal.

Remember that you need to use double backslashes in a string literal, and single backslashes in a regex literal to denote a literal backslash (needed for a regex escape).

"regex": "^\\+?([0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)$"
"regex": /^\+?([0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/

should work.

Upvotes: 1

Related Questions