[英]Regex that allows only one + sign at the beginning and then numbers
我需要匹配正則表達式,以使其在開頭以+(僅一個加號)開頭,然后僅允許數字。
這是我的指令:
(function(app) {
'use strict';
var plusOnly = function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(value) {
if (value) {
var digitsPlus = value.replace(/^\+[0-9]+/g, '');
if (digitsPlus !== value) {
ctrl.$setViewValue(digitsPlus);
ctrl.$render();
}
return parseInt(digitsPlus, 10);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
};
app.directive('plusOnly', [plusOnly]);
})(angular.module('App'));
HTML:
<input class="input" type="text" only-digits-with-plus="" ng-model="phone">
盡管這限制了數字和+,但仍然允許我有多個優點。
我在哪里犯錯?
謝謝。
您只需要將+限制為一個即可,如下所示:
^\+{1}[0-9]+$
在這里測試
編輯:
由於您的代碼邏輯存在問題...如果我對您的理解正確,那么您想刪除除正則表達式匹配的內容以外的所有內容。 實際上,您想要regex.Match
對面。 在這種情況下,您需要負前瞻,如下所示:
首先,檢查輸入是否有效,然后輸入是否有效...
var match = value.match(/^\+{1}[0-9]+$/g);
if (match !== null) {
//now replace values using negative lookahead...
var digitsPlus = value.replace(/^(?!\+{1}[0-9]+)$/g, '');
//some other code
那可能是您的問題的答案。
您的正則表達式是正確的。
您的函數中存在邏輯問題。
您正在使用輸入值(無論是什么),並且用空字符串替換輸入值+12321(任何數字),例如:
您要替換為abc的+ 43432abc。
但是反之亦然。
我建議做這樣的事情:
var digitsPlus = value.replace(/^.*?([\+0-9]?[0-9]+)?.*?$/, '$1');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.