如何使用jquery和regex验证小数字段? [英] How do I validate a decimal field with jquery and regex?
本文介绍了如何使用jquery和regex验证小数字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我到目前为止所拥有的:
this is what I have so far:
$j(element)..keypress(function(e){
var val = $j(this).val();
if (("1234567890.").indexOf(e.charCode) > -1){
if (val.length > 0){
var regex = /(\+|-)?(\d*\.\d*)/;
if (regex.test(val)){
return true;
} else {
return false;
}
} else {
return true;
}
} else {
return false;
}
});
但是由于某种原因,文本字段仅允许一个字符...甚至不允许输入数字
but for some reason, the text field only allows one character... and not even a number
推荐答案
在@elclanrs和@mgibsonbr的帮助下,我来到了这里:
With the help of @elclanrs and @mgibsonbr, I came to this:
$j = jQuery.noConflict();
$j(function() {
$j("input").keypress(function(e) {
var val = $j(this).val();
var regex = /^(\+|-)?(\d*\.?\d*)$/;
if (regex.test(val + String.fromCharCode(e.charCode))) {
return true;
}
return false;
});
});
可在此处进行测试: http://jsfiddle.net/9U2Mw/5/
这篇关于如何使用jquery和regex验证小数字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文