0
我想以這種方式驗證一個輸入字段,它不會接受除數字螞蟻'+'符號以外的任何內容。在尋找解決方案時,我發現了這個答案。 angularjs validate input and prevent change if invalid 它爲我工作,但我不能從我的瀏覽器的輸入字段中刪除任何東西,我已經寫了一些東西。無法通過退格或刪除按鈕刪除數據表單輸入字段
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>
我明白,在我的退格鍵好歹e.preventDefault()塊按鍵方法。我不知道如何處理這個問題,如何爲退格和刪除按鈕添加一種異常,所以e.preventDeafult()不會阻止它們。我可以在如何做到這一點方面有一些幫助嗎?
謝謝你這麼多的關鍵。不知何故,我甚至沒有像你那樣想解決方案。謝謝! – Martin