簡體   English   中英

angularjs驗證輸入並防止更改(如果無效)

[英]angularjs validate input and prevent change if invalid

我需要一個輸入字段,我只能輸入值1,2或3,因此我正在嘗試構建一個指令,如果它與這些值不匹配,則會阻止對模型的所有更改。
例如,值為1,我將其更改為5,它應該仍為1。

我把一個小小提琴http://jsfiddle.net/kannix/Q5YKE/放在一起但是使用$解析器很可能是錯誤的。

app.directive('myvalidator', function () {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {
            var validValues = [1,2,3];
            ctrl.$parsers.push(function (value) {
                if (validValues.indexOf(value) === -1){
                    //what to do here? should refuse wrong value and leave the old one
                }   
            });
        }
    }   

})

我最近為此寫了一個指令。 它需要一個regExp對象來驗證傳入的按鍵,並且只有在有效時才允許它們:

// forces keystrokes that satisfy the regExp passed
app.directive("regExpRequire", function() {

    var regexp;
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            regexp = eval(attrs.regExpRequire);

            var char;
            elem.on("keypress", function(event) {
                char = String.fromCharCode(event.which)
                if(!regexp.test(elem.val() + char))
                    event.preventDefault();
            })
        }
    }

})

模板用法: <input type="text" reg-exp-require="/^[a-zA-Z]$/">

或者在你的情況下: <input type="text" reg-exp-require="/^[1-3]*$/">

我建議使用ng-pattern-restrict指令。

獲取庫並簡單地裝飾您的輸入:

<input type="text" pattern="[0-9]+" ng-pattern-restrict />

GitHub: AlphaGit / ng-pattern-restrict

你總是可以聽到keypress事件並阻止角色完成。 這是一個掠奪者

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.validValues = ['a','1','2'];
});

app.directive('myValidator', function ($parse) {
    return {
        scope: {
          validValues: '=validValues'
        },
        link: function (scope, elm, attrs) {
          elm.bind('keypress', function(e){
            var char = String.fromCharCode(e.which||e.charCode||e.keyCode), matches = [];
            angular.forEach(scope.validValues, function(value, key){
              if(char === value) matches.push(char);
            }, matches);
            if(matches.length == 0){
              e.preventDefault();
              return false;
            }
          });
        }
    }   
});

我實際上必須建立並修改Ian Haggerty的答案形式。 他的代碼運作良好,直到我開始以不同的方式測試它。 我特意試圖測試低於100的值,但我得到了一些奇怪的結果。

如果我的輸入中有100,那么嘗試插入一個十進制數使其成為10.0,Ian的修復程序沒有考慮到這一點,並說它不匹配我的正則表達式(即使我允許最多兩位小數)。 事實證明它總是附加我在它正在測試的字符串的END處按下的字符,即使我將它插入中間。

我的更改是將原始值存儲在“keypress”上,然后存儲在“keyup”上(或者如果您願意,則“更改”),它會檢查新值。 如果無效,則恢復原始狀態。

不幸的是,它會簡單地更新模型,但至少它允許您在輸入值的中間或開頭鍵入字符,並且仍然可以正確匹配正則表達式。 在Angular 1.3中,我們可以使用ng-model-options =“{debounce:250}”來解決這個問題。 任何依賴於此模型更改的代碼都是無能為力的幫助。

usage: <input ... validate-with="/^([\d]{1,2}\.[\d]{1,2}|\.?[\d]{1,2}|100)?$/" />

.directive("validateWith", [function(){
    return {
        restrict: "A",
        link: function($scope, $el, $attrs){
            var regexp = eval($attrs.validateWith);
            var origVal;
            // store the current value as it was before the change was made
            $el.on("keypress", function(e){
                origVal = $el.val();
            });

            // after the change is made, validate the new value
            // if invalid, just change it back to the original
            $el.on("keyup", function(e){
                if(!regexp.test($el.val())){
                    $el.val(origVal);
                }
            });
        }
    }
}]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM