` ~ ! @ # $ % ^ & * ( ) _ + = { } | [ ] \ : ' ; " < > ? , . /
我想在输入文本字段中限制上面提到的特殊字符和数字。
ng-pattern="/^[a-zA-Z ]*$/"
限制特殊字符。此模式阻止所有特殊字符。当我想输入名字“PérezGil”时我面临问题我不想限制其他语言文字。
答案 0 :(得分:9)
<强>更新强>
我认为$解析器是最好的选择。请参阅更新的代码和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的更新示例
https://plnkr.co/edit/eEOJLi?p=preview
旧答案:
由于您已经有一个要限制的字符列表,您可以在ng-pattern表达式拼写出来,如:
控制器
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的一个工作示例
答案 1 :(得分:1)
Use Directives to restrict Special characters:
angular.module('scPatternExample', [])
.controller('scController', ['$scope', function($scope) {
}])
.directive('restrictSpecialCharactersDirective', function() {
function link(scope, elem, attrs, ngModel) {
ngModel.$parsers.push(function(viewValue) {
var reg = /^[a-zA-Z0-9]*$/;
if (viewValue.match(reg)) {
return viewValue;
}
var transformedValue = ngModel.$modelValue;
ngModel.$setViewValue(transformedValue);
ngModel.$render();
return transformedValue;
});
}
return {
restrict: 'A',
require: 'ngModel',
link: link
};
});
In Html:
<input type="text" ng-model="coupon.code" restrict-Special-Characters-Directive>
答案 2 :(得分:0)
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<input type="text" ng-change="Check(myValue)" ng-model="myValue" />
<p ng-show="test">The Special Character not accept.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope,ngModel) {
$scope.Check= function(x) {
var reg = /^[^`~!@#$%\^&*()_+={}|[\]\\:';"<>?,./]*$/;
if (!x.match(reg)) {
$scope.myValue = x.substring(0, x.length-1);
$scope.test=true;
}
else
{
$scope.test=false;
}
};
}]);
</script>
</body>
</html>