0

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:

 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()

How can I validate that the values in field "myfieldThatNeedNumbers" are numbers?

Thanks a ton!

user638009
  • 223
  • 1
  • 9
  • 25
  • This [previous answer on StackOverflow](http://stackoverflow.com/a/1830844/304588) (Validate numbers in JavaScript - IsNumeric()) may be of some help. – Richard Neil Ilagan Jun 21 '12 at 06:48

4 Answers4

1

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());
})
Liangliang Zheng
  • 1,763
  • 11
  • 16
1
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).

Also, $.ajax expects an object for the data parameter, so you need the following:

var data = {
    'myFieldsThatAreNumbers': params
};

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

Or just:

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

And jQuery will take care of creating the string for you.

Community
  • 1
  • 1
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
0
   $(".myfieldThatNeedNumbers").each(function(){
        var value = $(this).val();
        if($.isNumeric(value)) {
           myAray.push(value);   
        } else {
           alert('Not number')
        }
    });

Read more about $.isNumeric()

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0
/^\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)
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
Paul Marrington
  • 557
  • 2
  • 7