gpt4 book ai didi

javascript - 限制正斜杠的指令

转载 作者:行者123 更新时间:2023-12-01 01:46:58 26 4
gpt4 key购买 nike

我创建了一个不允许使用 spl 字符的指令(下划线和空格除外)。一切正常,但它也允许正斜杠。我在这里缺少什么?

下面是我的指令和plunkr:http://plnkr.co/edit/ho6kztdlYau4Zi29Afa5?p=preview

.directive('noSpecialChar', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue === undefined)
return ''

regReplace = new RegExp('[^\\w_/\s/g]', 'ig');
if (inputValue === undefined)
return ''
cleanInputValue = inputValue.replace(regReplace, '');
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;

});
}
}
});

最佳答案

你的正则表达式没有正确构建,如果你想替换除 \w_ 之外的所有内容,你应该使用这个相反:[^\w_](当然是转义的)。

将代码中的正则表达式替换为以下代码:

new RegExp('[^\\w_ ]', 'gi')

Note on \s: the \s matches not only regular space chars () but it also matches other types of empty space as well (\r\n\t\f\v). So, I believe you should not use it as you seem not to want other kind of white space being allowed on your input.

检查下面的工作代码。

angular.module('app', [])
.controller('myCtrl', function($scope) {
$scope.username = '';
})
.directive('noSpecialChar', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
if (inputValue === undefined)
return ''

regReplace = new RegExp('[^\\w_ ]', 'gi');
if (inputValue === undefined)
return ''
cleanInputValue = inputValue.replace(regReplace, '');
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;

});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<div ng-app="app" ng-controller="myCtrl">
Username : <input type="text" no-special-char ng-model="username" name="userName">
</div>

关于javascript - 限制正斜杠的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51878685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com