简体   繁体   English

javascript / jQuery:验证来自.val()的数字

[英]javascript/jQuery: validating numbers coming from .val()

I'm validating my form, just checking if in the fields where a number should be the user has entered an string. 我正在验证我的表单,只是检查用户是否应该在其中输入数字的字段中输入了字符串。 But as I'm getting all the field values like this: 但是随着我得到所有这样的字段值:

var number=  $("#number").val();

All my variables are strings. 我所有的变量都是字符串。

alert(typeof number);

shows "string" with all numeric fields values. 显示带有所有数字字段值的“字符串”。

Any ideas on how can I validate integers?? 关于如何验证整数的任何想法?

Thanks a lot 非常感谢

You can use 您可以使用

jQuery.isNumeric( value ) 

method for this purpose. 为此目的的方法。 As a result you don't need any extra parsing effort. 因此,您不需要任何额外的解析工作。

DEMO 演示

Read more about $.isNumeric() 阅读有关$.isNumeric()更多信息。

For manual parse(if you don't use above) 手动解析(如果您不使用上面的内容)

var number = parseInt($("#number").val(), 10);

and for check 和检查

if(isNaN(number)) {
   // do something
} else {
   // do something else
}

isNaN(parseInt($("#number").val())); should do the trick! 应该做的把戏! If you want to work with the number at all, this might be an easier way: 如果您想使用所有数字,这可能是一种更简单的方法:

var value = parseInt($("#number").val());

if (isNaN(value)) {
  console.log("invalid input");
} else {
  console.log("user entered: " + value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM