除了/之外不允许特殊字符到期日期

时间:2016-01-13 21:36:57

标签: javascript angularjs regex angularjs-directive

我写了一个指令,除了' /'之外不应该允许任何特殊字符。这是为有效期而写的,因此不应允许除数字之外的任何内容。我成功了,但它仍然允许特殊字符。以下是我的代码:

appModule.directive('numbersSlash', [function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                // this next if is necessary for when using ng-required on your input.
                // In such cases, when a letter is typed first, this parser will be called
                // again, and the 2nd time, the value will be undefined
                if (inputValue === undefined) {
                    return '';
                }
                // A regular expression validates the use of numbers
                var transformedInput = inputValue.replace(/[^/\0-9]/g, '');
                // If slash at first
                if(transformedInput =="/"){
                  transformedInput = '';
                }
                if (transformedInput !== inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }
                return transformedInput;
            });
        }
    };
}]);

请告知我的正则表达式模式可以进行哪些更改。目前它允许特殊字符和多个/.

1 个答案:

答案 0 :(得分:0)

要匹配01/20,请尝试使用正则表达式/\d\d\/\d\d/g 1
例如。 http://regexr.com/3ciqh

不是剥离,而是尝试匹配:

var isValid = /^(\d\d\/\d\d)$/.test('01/20');
// true

var isValid = /^(\d\d\/\d\d)$/.test('$1/20');
// false

1 可能有更优雅的方法。