customizing指令限制用户输入特殊字符:angular Js

shr*_*nsh 5 javascript regex special-characters angularjs angularjs-directive

我正在详细了解angularJs指令.目前我用它来限制用户不要输入特殊字符.

这是代码

HTML

<input type="text" no-special-char ng-model="vm.customTag" class="form-control" value="" />
Run Code Online (Sandbox Code Playgroud)

AngularJS指令

app.directive('noSpecialChar', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                if (inputValue == null)
                    return ''
                cleanInputValue = inputValue.replace(/[^\w\s]/gi, '');
                if (cleanInputValue != inputValue) {
                    modelCtrl.$setViewValue(cleanInputValue);
                    modelCtrl.$render();
                }
                return cleanInputValue;
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

这是我想要的两件事

(1)用户可以输入'-'当前没有发生的减号/破折号,如何改变我/[^\w\s]/gi允许用户输入的符号(短划线/减号).

(2)上述功能仅限制用户不输入任何特殊字符,但当用户键入特殊字符时,我想显示红色警告以及"不允许使用特殊字符",我该怎么做?

任何帮助表示赞赏!

谢谢

Kas*_*Lee 0

问题#1

目前,您的正则表达式正在选择所有不是 ( [^) 单词字符 ( \w) 或空格 ( \s) 的字符。要包含 a -,需要将其包含在不被替换的字符列表中。

尝试以下正则表达式:

/[^\w\s-]/gi
Run Code Online (Sandbox Code Playgroud)

要排除任何其他字符被删除,只需将它们添加到-

Live Demo on RegExr


问题2

您需要监听keypress表单上的事件,以查看每次内容更改。然后您可以使用它.match()来查看是否存在任何特殊字符。如果它们这样做,它将返回一个字符串,即truthy,如果不是,它将返回false

.match()您可以检查语句中的结果if,如果匹配特殊字符,请添加您的消息。

if (inputValue.match(/[^\w\s]/gi)) {
    // Add Alert Here!
}
Run Code Online (Sandbox Code Playgroud)

或者,在您的 内部if (cleanInputValue != inputValue),您可以添加代码来创建警报。你的if陈述基本上给出了与该方法相同的结果.match()。它检测字符串是否已被更改,.replace()如果更改则运行里面的代码