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,914
  • 26
  • 42
Nazmul Hasan
  • 6,540
  • 13
  • 34
  • 36

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ó
  • 769,263
  • 179
  • 909
  • 832
19

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

Michael Schmidt
  • 8,723
  • 13
  • 54
  • 79
Massimo
  • 191
  • 1
  • 3
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,029
  • 3
  • 21
  • 40
0
^\+?\d*.{0,1}\d+$

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

Jeff Meatball Yang
  • 35,999
  • 26
  • 90
  • 121
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
  • 6
0

ok, try this;

\+?\d*\.?\d+\b
Emre Erkan
  • 8,372
  • 3
  • 49
  • 53