0

我有一个ng-pattern来强制执行特定格式(例如,IP v4 地址):

<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>

数据来自数据库,但假设需求发生了变化,现在应该存储IPv6 。我本来希望更改正则表达式,但它会删除输入的内容!检查这个 plunker(在那里你可以看到丢失内容的效果):http ://plnkr.co/edit/UPrU35

这与将输入切换为必需是一样的,我只需要用户遵守新规则。

问题:

应该如何继续应用 ng-pattern 但仍保持 ng-model 绑定? (我希望表单输入无效,但不以丢失以前的内容为代价)

4

1 回答 1

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.

于 2014-04-02T16:44:13.437 回答