Nazmul Hasan
Nazmul Hasan

Reputation: 7040

Positive number validation in jquery

I have used an expression for validating a positive number as follows:

^\d*\.{0,1}\d+$

when I give it an input of -23, it will mark input as negative, but when I give it an input of +23, it will mark it as invalid number!

what is the problem?

Can anyone give a solution that With +23 it will return (positive)?

Upvotes: 20

Views: 51223

Answers (7)

Easiest way is

$( "#myform" ).validate({
  rules: {
    field: {
      required: true,
      digits: true
    }
  }
});

ref : digits method | jQuery Validation Plugin --> https://jqueryvalidation.org/digits-method/

Upvotes: 4

Massimo
Massimo

Reputation: 179

Or simply use: min: 0.01.
For example for money

Upvotes: 19

amber
amber

Reputation: 1137

Since I'm looking for something similar, this will test for a positive, non-zero value with an optional leading plus (+) sign.

^\+?[1-9][0-9]*$

This does not match decimal places nor does it match leading zeros.

Upvotes: 1

Emre Erkan
Emre Erkan

Reputation: 8482

ok, try this;

\+?\d*\.?\d+\b

Upvotes: 0

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827436

Have you considered to use anything beside regular expressions?

If you are using the jQuery Validation Plugin you could create a custom validation method using the Validator/addMethod function:

$.validator.addMethod('positiveNumber',
    function (value) { 
        return Number(value) > 0;
    }, 'Enter a positive number.');

Edit: Since you want only regular expressions, try this one:

^\+?[0-9]*\.?[0-9]+$

Explanation:

  • Begin of string (^)
  • Optional + sign (\+?)
  • The number integer part ([0-9]*)
  • An optional dot (\.?)
  • Optional floating point part ([0-9]+)
  • End of string ($)

Upvotes: 39

Martin Jansen
Martin Jansen

Reputation: 276

If you insist on using a regular expression, please make sure that you also capture numbers with exponents and that you allow numbers of the form .42, which is the same as 0.42.

^+?\d*.?\d+([eE]+?\d+)?$

should to the trick.

Upvotes: 0

Jeff Meatball Yang
Jeff Meatball Yang

Reputation: 39037

^\+?\d*.{0,1}\d+$

Gets you the ability to put a "+" in front of the number.

Upvotes: 0

Related Questions