我试图以这种方式验证一个输入字段,除了数字蚂蚁' +'之外它不会接受任何内容。标志。在寻找解决方案时,我找到了这个答案。 angularjs validate input and prevent change if invalid 它对我有用,但在我写完文章之后,我无法从浏览器中的inputfield中删除任何内容。
var app = angular.module('ContactUsScreen', ['ngMessages']);
app.controller('ContactUsScreenController', function($scope, $http) {
$scope.validValues = ['+', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
});
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;
}
});
}
}
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="ContactUsScreen" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px;
}
textarea {
resize: none;
}
</style>
<script src="js/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-messages.js"></script>
<script src="js/contact.js"></script>
</head>
<body ng-app="app" ng-controller="ContactUsScreenController">
<div id="formDiv" class="container">
<form ng-submit="submitForm()" id="contactForm" name="contactForm" class="form-horizontal" novalidate>
<div class="form-group" id="inputPhoneDiv" ng-class="{ 'has-error': contactForm.phoneNr.$invalid && !contactForm.phoneNr.$pristine}">
<label for="inputPhone" class="col-xs-2">Phone number</label>
<div class="col-xs-10">
<input type="text" my-validator valid-values="validValues" name="phoneNr" class="form-control" id="inputPhone">
</div>
</div>
</form>
</div>
&#13;
据我所知,在某种程度上,e.preventDefault()会阻止我的退格按钮的按键方法。我无法弄清楚如何处理这个,如何为退格和删除按钮添加一些异常,所以e.preventDeafult()不会阻止它们。我可以帮忙解决一下这个问题吗?
答案 0 :(得分:2)
为什么不简单地做这样的事情?
link: function(scope, elm, attrs) {
elm.bind('keypress', function(e) {
var key = e.keyCode || e.charCode;
if( key == 8 || key == 46 )
return true;
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;
}
});
如果它是您信任的密钥(如退格键),则无需运行整个逻辑