簡體   English   中英

到期日期不允許使用特殊字符,但/

[英]Not allow special characters in expiration date except /

我寫了一條指令,除了“ /”外,不允許任何特殊字符。 這是為截止日期而寫的,因此除數字外不應允許其他任何內容。 我已經成功了,但仍然允許使用特殊字符。 下面是我的代碼:

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;
            });
        }
    };
}]);

請告知可以對我的正則表達式模式進行哪些更改。 當前,它允許特殊字符和多個/。

要匹配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可能有更多優雅的方法可以做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM