验证文本字段是否为数字jQuery [英] Validate that text field is numeric usiung jQuery
本文介绍了验证文本字段是否为数字jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的问题-如果不为空,我想检查一个字段是否为整数.我没有使用任何其他插件,只是jQuery.我的代码如下:
I have a simple issue -- I would like to check a field to see if it's an integer if it is not blank. I'm not using any additional plugins, just jQuery. My code is as follows:
if($('#Field').val() != "")
{
if($('#Field').val().match('^(0|[1-9][0-9]*)$'))
{
errors+= "Field must be numeric.<br/>";
success = false;
}
}
...似乎无效.我要去哪里错了?
...It doesn't seem to work. Where am I going wrong?
我收到的错误是val() is not an object
.
事实证明,真正的问题是我设置了元素名称而不是ID.
It turned out that the real issue was that I had my element name set and not the Id.
推荐答案
这应该有效.我会首先从输入字段中修剪空白:
This should work. I would trim the whitespace from the input field first of all:
if($('#Field').val() != "") {
var value = $('#Field').val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
errors += "Field must be numeric.<br/>";
success = false;
}
} else {
errors += "Field is blank.</br />";
success = false;
}
这篇关于验证文本字段是否为数字jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文