gpt4 book ai didi

javascript + 正则表达式

转载 作者:行者123 更新时间:2023-11-30 00:32:25 26 4
gpt4 key购买 nike

我有一个问题。我想使用一个正则表达式,让我只介绍数字和“。” (对于小数)在输入字段上,没有字母和其他特殊字符。

我正在尝试这个:

选项 1 => var restrict="[^\d+]"

选项 2 => var restrict="[^\d+]"

iAttrs.restrict = ^(?![0-9]+([.]?[0-9]+))$

value.toLowerCase().replace(new RegExp(iAttrs.restrict, 'g'), '');

这个正则表达式是一个 Angular Directive(指令)

appModule.directive('restrict', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, iElement, iAttrs, controller) {
scope.$watch(iAttrs.ngModel, function(value) {
if (!value) {
return;
}
value = value.toString();
$parse(iAttrs.ngModel).assign(scope, value.toLowerCase().replace(new RegExp(iAttrs.restrict, 'g'), ''));
});
}
}
});

它必须删除输入中的错误字符。但问题是

选项 1 ==> 不要让我写“.”性格

选项 2 ==> 不要让我什么都不写(当我有一个默认值示例时:“300.21”必须出现在输入字段中......在 restrict 指令完成后,输入中没有任何内容。

有人可以帮帮我吗?

谢谢

最佳答案

Updated based on comments:

由于小数点的情况非常特殊,我为此创建了一个新指令。

指令代码:

angular.module("app",[]).directive('allowOnlyDecimal', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, iElement, iAttrs, controller) {
// used to find out if more than one . is available
function nth_ocurrence(str, needle, nth) {
for (i=0;i<str.length;i++) {
if (str.charAt(i) == needle) {
if (!--nth) {
return i;
}
}
}
return false;
}

scope.$watch(iAttrs.ngModel, function(value) {
if (!value) {
return;
}
value = value.toString();
var temp = value.replace(/[^(\d\.)]/gi, '');
// this removes any special character and alphabets
if(nth_ocurrence(temp,".",2)) {
temp = temp.substr(0, nth_ocurrence(temp,".",2));
// removes if user enters more than one decimal point
}
scope[iAttrs.ngModel] = temp;
});
}
};
}).controller("MainController", function($scope) {
$scope.someInput = 100.400;
});

在您的 HTML 中:

<input type="text" ng-model="someInput" allow-only-decimal>

WORKING DEMO

OLD ANSWER:

这可能是更通用的方法,您可以使用正则表达式将其用于大多数限制功能。

HTML:

<input type="text" ng-model="someInput" restrict="[^(\d\.)]">

JS:

angular.module("app",[]).directive('restrict', function($parse, $timeout) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, iElement, iAttrs, controller) {
scope.$watch(iAttrs.ngModel, function(value) {
if (!value) {
return;
}
value = value.toString();
$timeout(function() {
scope[iAttrs.ngModel] = value.replace(new RegExp(iAttrs.restrict,'gi'), '');


},10);
});
}
};
}).controller("MainController", function($scope) {
$scope.someInput = 100.400;
});

关于javascript + 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28879865/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com