0

I have a ng-pattern to enforce a particular format (for instance, IP v4 address):

<input ng-model="ip" 
       ng-pattern="/(([2][0-5]{2}|[2][0-4]\d|[01]?\d{0,2})\.){3}([2][0-5]{2}|[2][0-4]\d|[01]?\d{0,2})/">
</input>

The data comes from the DB but let's say that the requirement evolved and now IPv6 should be stored. I would have expected changing the regular expression but it removes the content of the input! Check this plunker (where you can see the losing-content effect): http://plnkr.co/edit/UPrU35

It is kind of the same thing as switching an input to required, I simply need users to comply to the new rules.

Question:

How should one proceed to apply ng-pattern but still keep the ng-model binding? (I want the form input to be invalid but no at the cost of losing its former content)

Guillaume
  • 277
  • 5
  • 15

1 Answers1

0

I do not quite understand what exactly you require , however i see a problem in the code ,

You are using the same model on 3 different input tags , which is not advisable. I would suggest using something like this ,

<label>No pattern</label>
  <input ng-model="ip4.test1"></input><br>

  <!-- Pattern 1 -->
  <label>Pattern (IP v4)</label>
  <input ng-model="ip4.test2" ng-pattern="/(([2][0-5]{2}|[2][0-4]\d|[01]?\d{0,2})\.){3}([2][0-5]{2}|[2][0-4]\d|[01]?\d{0,2})/"></input><br>

  <!-- Pattern 2 -->
  <label>Changed pattern (IP v6)</label>
  <input ng-model="ip4.test3" ng-pattern="/([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4}/"></input><br>

By doing this , you can avoid the losing other input fields , plus you get the ng-pattern validation.

And in your JS file , you can use them something like this ,

$scope.ipv4 = {

 test1 : <value> , 
 test2 : <value>,
 test3 : <value>}; 

And access its value like this ,

var temp = $scope.ipv4.test1;

Hope this solves your problem.

user1537766
  • 162
  • 7
  • So, whenever I need to change validation rules (using ng-pattern) on the frontend side, you suggest I place 2 inputs which each pattern and map the one with the new pattern into DB? – Guillaume Apr 03 '14 at 04:01
  • 1
    Depends on what u want to achieve , if u want to just change the ng-pattern validation and dont care about losing the old value , then you can do that using a single tag , and provide a variable to ng-pattern instead of giving the pattern inline. – user1537766 Apr 03 '14 at 04:05