限制 HTML 中的特殊字符 &AngularJS [英] Restrict Special Characters in HTML & AngularJs
问题描述
` ~ ! @ # $ % ^ & * ( ) _ + = { } | [ ] \ : ' ; " < > ? , . /
我想限制输入文本字段中的上述特殊字符和数字.我用了
I want to restrict the above mentioned special characters and numbers in the input text field. I used the
ng-pattern="/^[a-zA-Z ]*$/"
限制特殊字符.此模式阻止了所有特殊字符.我想输入姓名Pérez Gil"时遇到问题,我不想限制其他语言文本.
to restrict the special characters. This pattern is blocking all the special characters. I am facing issue when I want to enter name "Pérez Gil" I don't want to restrict other language text.
推荐答案
更新:
我认为 $parsers 是这里最好的选择.查看更新的代码和plunker.
I think $parsers is the best options here. See the updated code and plunker.
控制器
angular.module('ngPatternExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.regex = /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
}])
.directive('myDirective', function() {
function link(scope, elem, attrs, ngModel) {
ngModel.$parsers.push(function(viewValue) {
var reg = /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
// if view values matches regexp, update model value
if (viewValue.match(reg)) {
return viewValue;
}
// keep the model value as it is
var transformedValue = ngModel.$modelValue;
ngModel.$setViewValue(transformedValue);
ngModel.$render();
return transformedValue;
});
}
return {
restrict: 'A',
require: 'ngModel',
link: link
};
});
模板
<input type="text" ng-model="model" id="input" name="input" my-directive />
这是一个关于 Plunker 的更新示例
Here's a updated example on Plunker
https://plnkr.co/edit/eEOJLi?p=preview
旧答案:
由于您已经有了要限制的字符列表,您可以将它们拼写在 ng-pattern 表达式中,例如:
Since you already have a list of characters that you want to restrict, you can spell them out in the ng-pattern expression like:
控制器
angular.module('ngPatternExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.regex = /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./1-9]*$/;
}]);
模板
<input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" />
这是一个关于 Plunker 的工作示例
Here's a working example on Plunker
https://plnkr.co/edit/eEOJLi?p=preview
这篇关于限制 HTML 中的特殊字符 &AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!