angularjs validate input and prevent change if invalid

前端 未结 4 1702
野性不改
野性不改 2021-01-06 11:15

I neeed an input field where I can enter only the values 1,2 or 3 so i\'m trying to build a directive which prevents all changes to the model if it doesn\'t match these valu

4条回答
  •  耶瑟儿~
    2021-01-06 12:08

    I recently wrote a directive just for this. It takes a regExp object that validates the incoming key presses and only permits them if are valid:

    // 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();
                })
            }
        }
    
    })
    

    Template usage:

    Or in your case:

提交回复
热议问题