2013-09-30 112 views
3

字母數字和點我怎麼能只允許字母數字字符和點的範圍允許範圍

<input type="text" ng-model="test" /> 

腳本

$scope.myFn = function(){ 
if($scope.test != ''){ 
alert("Please use only Alphanumeric characters or dots") 
} 

} 

回答

2
if (/[^a-zA-Z0-9\.]/.test($scope.test)) { 
     alert("Please use only Alphanumeric characters or dots") 
    } 
7

更好的辦法是在HTML定義ng-pattern輸入元素。這不會允許在模型上設置不正確的值。我沒有測試正則表達式模式。

<input type="text" ng-model="test" ng-pattern="/[a-zA-Z0-9\.]*/"/> 
+2

正則表達式需要被錨定:'ng-pattern =「/^[a-zA-Z0-9 \。] * $ /」' – ouranos

相關問題