javascript - 限制正斜杠的指令
问题描述
我创建了一个不允许 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')
注意
\s
:\s
不仅匹配常规空格字符( ),而且还匹配其他类型的空格(
\r\n\t\f\v
)。所以,我相信你不应该使用它,因为你似乎不希望在你的输入中允许其他类型的空白。
检查下面的工作代码。
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 - 必须在索引处为表单控件提供一个值:0 反应式表单
- javascript - Web 音频 API 卷积器节点的相位问题
- ios - stopAccessingSecurityScopedResource 似乎是永久性的
- javascript - 为什么 amp-sidebar 会导致未定义错误的“hiddenElementInfos”?
- hibernate - Kotlin 与休眠 java.io.NotSerializableException
- node.js - 在 QNAP NAS 上静态部署 VueJS (Vue-CLI) SPA
- javascript - 将文件加载到 blob 中以压缩和上传
- kubernetes - .net core 2.2 ConnectAsync 抛出 No such device or address 异常
- css - 使用 IOS 或其他移动设备单击元素时,SVG 图像未更改。在 PC / Mac 上运行良好
- typescript - vuex 懒加载数据