javascript 将输入字段中的字符限制为一组字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25413145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Restricting Characters in Input Field to a Set of Characters
提问by Kyle V.
Question Update:How can I prevent all characters except for the ones specified in a char array from being typed into an input field using AngularJS (or jQuery)?
问题更新:如何使用 AngularJS(或 jQuery)防止除 char 数组中指定的字符之外的所有字符输入到输入字段中?
Old Question:
老问题:
I have a simple <input type="text" />
field in my AngularJS application and I want the user to only be able to enter the following characters into the field:
我的<input type="text" />
AngularJS 应用程序中有一个简单的字段,我希望用户只能在该字段中输入以下字符:
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ !\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
I know that I can add ng-pattern="allowed"
to the <input>
and then set $scope.allowed
to some regex pattern and that will mark the input invalid if any invalid characters are entered, but I also want to prevent restricted characters from being input into the field AT ALL.
我知道我可以添加ng-pattern="allowed"
到<input>
然后设置$scope.allowed
为一些正则表达式模式,如果输入了任何无效字符,这会将输入标记为无效,但我也想完全防止将受限字符输入到字段中。
So my question is composed of two questions:
所以我的问题由两个问题组成:
- What regex pattern do I use to restrict the character set to the one I posted above?
- How do I prevent illegal characters from being entered in the field? (e.g. if you type a lowercase letter then it won't appear in the field to begin with, similarly if you try to paste in text containing any illegal characters they will be removed immediately)
- 我使用什么正则表达式模式将字符集限制为我上面发布的那个?
- 如何防止在字段中输入非法字符?(例如,如果您键入小写字母,则它不会出现在开头的字段中,同样,如果您尝试粘贴包含任何非法字符的文本,它们将立即被删除)
采纳答案by Viktor Bahtev
To 'restrict some characters from being typed in' what comes in my mind is to attach event handlers for 'keyup', 'change', 'paste' events on inputs and when they are triggered to 'clean' their values against your pattern. I implemented the logic as jQuery plugin but you can adapt it to angular, use better naming or whatever you want.
为了“限制输入某些字符”,我想到的是在输入上附加“keyup”、“change”、“paste”事件的事件处理程序,以及当它们被触发以根据您的模式“清除”它们的值时。我将逻辑实现为 jQuery 插件,但您可以将其调整为 angular,使用更好的命名或任何您想要的。
The plugin:
插件:
$.fn.restrictInputs = function(restrictPattern){
var targets = $(this);
// The characters inside this pattern are accepted
// and everything else will be 'cleaned'
// For example 'ABCdEfGhI5' become 'ABCEGI5'
var pattern = restrictPattern ||
/[^0-9A-Z !\"#$%&'()*+,\-.\/:;<=>?@\[\]^_`{|}~]*/g; // default pattern
var restrictHandler = function(){
var val = $(this).val();
var newVal = val.replace(pattern, '');
// This condition is to prevent selection and keyboard navigation issues
if (val !== newVal) {
$(this).val(newVal);
}
};
targets.on('keyup', restrictHandler);
targets.on('paste', restrictHandler);
targets.on('change', restrictHandler);
};
Usage:
用法:
$('input').restrictInputs();
// Or ...
$('.my-special-inputs-decorated-with-this-class').restrictInputs();
Here is a JsFiddle Demo
这是一个JsFiddle 演示
Note: you can try to change the implementation to accept string with forbidden characters instead of regular expression and create the regex dynamically. Also you may find others events which are appropriate for triggering the 'cleaning'.
注意:您可以尝试更改实现以接受带有禁用字符的字符串而不是正则表达式并动态创建正则表达式。您还可以找到适合触发“清理”的其他事件。
回答by Beyers
The Angular way to do this is to make use of Angular's ngModelController.$parsers See the documentation:
Angular 的方法是利用 Angular 的 ngModelController.$parsers 看文档:
$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.
$解析器
每当控件从 DOM 读取值时,作为管道执行的函数数组。依次调用每个函数,将值传递给下一个。最后一个返回值用于填充模型。用于清理/转换值以及验证。对于验证,解析器应使用 $setValidity() 更新有效性状态,并为无效值返回 undefined。
Here is an example of a re-usable directive using this approach:
这是使用这种方法的可重用指令的示例:
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);
}
};
}
]);
Here is a plnkr demo.
这是一个plnkr 演示。
*Regex pattern for the above directive taken from Viktor Bahtev answer.
*上述指令的正则表达式模式取自 Viktor Bahtev 的回答。
You can obviously extend this directive to take an input parameter as well. I'll leave that for your exersize.
显然,您也可以扩展此指令以获取输入参数。我会把它留给你的锻炼。