tsr
tsr

Reputation: 45

jquery - allow only negative, positive or decimal number validation

I need a javascript/jQuery routine that validates a string to allow only negative, positive or decimal numbers(ex. -1 or -41.02 or 20 or 2.20 or 10.05)

Upvotes: 1

Views: 5032

Answers (3)

tsr
tsr

Reputation: 45

The regular expression given below solves the issue, it works for -ve decimal numbers.

^-?[0-9]{0,4}(.^-[0-9]{1,4})?$|^(100)(.^-[0]{1,4})?$

Upvotes: 1

Shamim Hafiz - MSFT
Shamim Hafiz - MSFT

Reputation: 22114

One way to do this is to parse the value and see if you get a valid number.

You can also use regular expression for even more complex data type matching.

Try the following:

[-+]?([0-9]*\.[0-9]+|[0-9]+)

Also look here for further information.

Upvotes: 0

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18354

function validate(str){
   var fvalue = parseFloat(str);
   return !isNaN(fvalue) && fvalue != 0;
}

Upvotes: 4

Related Questions