需要 3 个正则表达式来不允许数字、字母和特殊字符

Need 3 regex for not allowing number, not allowing alphabets and not allowing special character

我想为输入字段创建 angular js 指令,该指令可配置为允许数字或字母或特殊字符。例子

HTML <input type="text" ng-model="ctrl.inputField" is-alphabets-allowed="false" is-numbers-allowed="true"is-special-characters-allowed="false"

指令

angular.module('forms').directive('inputFieldConstraint', nputFieldConstraint);
InputFieldConstraint.$inject = ['constraintsService'];

function InputFieldConstraint(constraintsService) {
    return {
        restrict: 'EA',
        require: 'ngModel',
        scope: {
            isAlphabetsAllowed: '=',
            isNumbersAllowed: '=',
            isSpecialCharactersAllowed: '='
        },
        link: function (scope, ele) {
            $(ele).on('input', function () {
                var test = $(ele).val().replace(/[^a-bA-Z]/g, '');
                $(ele).val(test);
            });
        }
    }
}

请建议创建指令的最佳做法以及我应该为这 3 种情况使用哪个正则表达式?

这是一种方法 - 在 link() 期间,使用范围变量构建单个正则表达式,然后以编程方式应用新的 ng-pattern 指令:

    link: function (scope, ele) {
         const allowedClasses = [];
         const { isAlphabetsAllowed, isNumbersAllowed, isSpecialCharactersAllowed } = scope;

         if (isAlphabetsAllowed) allowedClasses.push("[a-zA-Z]");
         if (isNumbersAllowed) allowedClasses.push("/d+");
         if (isSpecialCharactersAllowed) allowedClasses.push("\^\$\(\)");

         const regexString = allowedClasses.join("");
         scope.regex = new RegExp(regexString, 'g');

         $(ele).attr('ng-pattern', 'regex'); //references our new scope.regex
    }

请注意,如果 isAlphabetsAllowed 等发生变化,您还需要更新 scope.regex 的值,因此您可能需要 $scope.watch() 或类似的值。

此外,为了确保此操作在 ng-pattern 指令触发之前发生,您需要确保指令的优先级高于 ng-pattern 的优先级,这是 0,所以我将 priority 设置为 1 以确保您先行。

ng 模式文档:https://docs.angularjs.org/api/ng/directive/ngPattern