简体   繁体   English

javascript / jQuery:使用.each时验证数字

[英]javascript/jQuery: validating numbers when using .each

Hi all, 大家好,

I'm validating my form, just checking if in the fields where a number should be the user has entered an string. 我正在验证我的表单,只是检查一个数字应该是用户输入字符串的字段。

In the form there is a field where the users can add more fields if needed. 在表单中有一个字段,用户可以根据需要添加更多字段。 Then the form is sent to a js function where I gather the fields added like this: 然后将表单发送到js函数,我在其中收集添加的字段,如下所示:

 params ='';   
var myAray = []; 
    $(".myfieldThatNeedNumbers").each(function(){
        myAray.push($(this).val());
    })
    params += '&myfieldThatNeedNumbers='+myAray;

Later params will be sent to my php file thanks to .ajax() 由于.ajax(),后来的params将被发送到我的php文件

How can I validate that the values in field "myfieldThatNeedNumbers" are numbers? 如何验证“myfieldThatNeedNumbers”字段中的值是否为数字?

Thanks a ton! 万分感谢!

or you can try 或者你可以试试

!isNaN(Number(value))

EDIT: Do you mean - 编辑:你的意思是 -

$(".myfieldThatNeedNumbers").each(function(){
    var val = $(this).val();
    if(!isNaN(Number(val)){ /* invalid number detected */ }

    myAray.push($(this).val());
})
var params = $( '.myFieldsThatAreNumber' ).filter( function() {
    return $.isNumeric( this.value );
} );

Elegant answer of the day™. 优雅的当天回答™。

$.isNumeric requires jQuery 1.7 ( source for the shim , probably based on this answer ). $.isNumeric需要jQuery 1.7( shim的源代码 ,可能基于这个答案 )。

Also, $.ajax expects an object for the data parameter, so you need the following: 此外, $.ajax期望data参数的对象,因此您需要以下内容:

var data = {
    'myFieldsThatAreNumbers': params
};

$.ajax( {
    data: data,
} );

Or just: 要不就:

$.ajax( {
    data: {
        'myFieldsThatAreNumbers': params
    },
} );

And jQuery will take care of creating the string for you. jQuery将负责为您创建字符串。

   $(".myfieldThatNeedNumbers").each(function(){
        var value = $(this).val();
        if($.isNumeric(value)) {
           myAray.push(value);   
        } else {
           alert('Not number')
        }
    });

Read more about $.isNumeric() 阅读更多关于$.isNumeric()

/^\d+$/.text(string)

for while numbers. 对于数字而言。

/^\d+\.?\d*$/.test(string)

for floating point. 对于浮点。 add [+\\-]? [+\\-]? at front if you need sign. 在前面,如果你需要签名。

For dollars you could use 对于你可以使用的美元

/^[+\-]?\d+(\.\d{2})?/.test(string)

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

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