gpt4 book ai didi

jquery - jquery中正十进制值和-1值的正则表达式

转载 作者:行者123 更新时间:2023-12-01 03:37:34 25 4
gpt4 key购买 nike

jquery 中正十进制值和 -1 值的正则表达式如何实现?我设法用这个来实现正负十进制值,但它只能是-1。有什么想法吗?

$(".SermeCoopValidarTope").keypress(function (e) {
var tecla = (document.all) ? e.keyCode : e.which;
var numeroDecimal = $(this).val();
if (tecla == 8) return true;

if (tecla > 47 && tecla < 58) {
if (numeroDecimal == "") return true
regexp = /^([0-9])*[.]?[0-9]{0,1}$/;
return (regexp.test(numeroDecimal))
}
if (tecla == 46) {
if (numeroDecimal == "") return false
regexp = /^[0-9]+$/
return regexp.test(numeroDecimal)
}
return false
});

最佳答案

将 or | 与两个匹配表达式一起使用来测试是否匹配。

我还根据当前值和新按键重写了代码来构造预期值。这大大简化了代码。

$(".SermeCoopValidarTope").keypress(function (e) {
var tecla = (document.all) ? e.keyCode : e.which;

var numeroDecimal = $(this).val();

// Allow backspace
if (tecla == 8) return true;

// if it's a valid character, append it to the value
if ((tecla > 47 && tecla < 58) || tecla == 45 || tecla == 46) {
numeroDecimal += String.fromCharCode(tecla)
}
else return false;

// Now test to see if the result "will" be valid (if the key were allowed)

regexp = /^\-1?$|^([0-9])*[.]?[0-9]{0,2}$/;
return (regexp.test(numeroDecimal));
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/Ld3n4b56/

更新为支持 , 而不是 . 作为小数分隔符:

$(".SermeCoopValidarTope").keypress(function (e) {
var tecla = (document.all) ? e.keyCode : e.which;

var numeroDecimal = $(this).val();

// Allow backspace
if (tecla == 8) return true;

// if it's a valid character, append it to the value
if ((tecla > 47 && tecla < 58) || tecla == 45 || tecla == 44) {
numeroDecimal += String.fromCharCode(tecla)
}
else return false;

// Now test to seee of the result will be valid

regexp = /^\-1?$|^([0-9])*[,]?[0-9]{0,2}$/;
return (regexp.test(numeroDecimal));
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/Ld3n4b56/1/

正则表达式的缩短版本(感谢@Brian Stephens):

句点小数分隔符:http://jsfiddle.net/Ld3n4b56/4/

/^(-1?|\d*.?\d{0,2})$/

逗号小数分隔符:http://jsfiddle.net/Ld3n4b56/3/

/^(-1?|\d*,?\d{0,2})$/

关于jquery - jquery中正十进制值和-1值的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29921794/

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