问题更新:如何防止使用 AngularJS(或 jQuery)将字符数组中指定的字符以外的所有字符输入到输入字段中?
老问题:
我的 AngularJS 应用程序中有一个简单的 <input type="text" />
字段,我希望用户只能在该字段中输入以下字符:
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~
我知道我可以将 ng-pattern="allowed"
添加到 <input>
,然后将 $scope.allowed
设置为某种正则表达式模式,如果输入任何无效字符,这会将输入标记为无效,但我还想防止将受限字符输入到字段 AT全部。
所以我的问题由两个问题组成:
- 我使用什么正则表达式模式来将字符集限制为我在上面发布的字符集?
- 如何防止在字段中输入非法字符? (例如,如果您键入一个小写字母,则它不会出现在字段开头,同样,如果您尝试粘贴包含任何非法字符的文本,它们将立即被删除)
最佳答案
Angular 的方法是利用 Angular 的 ngModelController.$parsers 参见 documentation :
$parsers
Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. Each function is called, in turn, passing the value through to the next. The last return value is used to populate the model. Used to sanitize / convert the value as well as validation. For validation, the parsers should update the validity state using $setValidity(), and return undefined for invalid values.
这是使用这种方法的可重用指令的示例:
app.directive('inputRestrictor', [
function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModelCtrl) {
var pattern = /[^0-9A-Z !\\"#$%&'()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g;
function fromUser(text) {
if (!text)
return text;
var transformedInput = text.replace(pattern, '');
if (transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
}
]);
这是一个plnkr demo .
*上述指令的正则表达式模式取自 Viktor Bahtev 的回答。
您显然可以扩展此指令以获取输入参数。我会把它留给你锻炼。
关于javascript - 将输入字段中的字符限制为一组字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25413145/