19

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

Mahdi Alkhatib
  • 1,954
  • 1
  • 29
  • 43
Nazmul Hasan
  • 6,840
  • 13
  • 36
  • 37

7 Answers7

39

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 ($)
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
19

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

Michael Schmidt
  • 9,090
  • 13
  • 56
  • 80
Massimo
  • 183
  • 1
  • 4
3

Easiest way is

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

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

  • Also an excelent one, like the answer from user1052072 - it also works, if you just add the ```digits``` class to the input. – Andreas Nov 08 '17 at 16:41
1

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.

amber
  • 1,067
  • 3
  • 22
  • 42
0
^\+?\d*.{0,1}\d+$

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

Jeff Meatball Yang
  • 37,839
  • 27
  • 91
  • 125
0

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.

Martin Jansen
  • 276
  • 1
  • 7
0

ok, try this;

\+?\d*\.?\d+\b
Emre Erkan
  • 8,433
  • 3
  • 48
  • 53