Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 565
Nazmul Hasan Avatar asked Jul 07 '09 04:07

Nazmul Hasan


People also ask

How to allow only Positive numbers in input type number?

As we know, the <input type="number"> specifies a field for entering a number. If you want to restrict the <input> field to only positive numbers, you can use the min attribute.

Is number validation in jQuery?

The jQuery $. isNumeric() method is used to check whether the entered number is numeric or not. $. isNumeric() method: It is used to check whether the given argument is a numeric value or not.


2 Answers

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 ($)
like image 121
Christian C. Salvadó Avatar answered Oct 16 '22 07:10

Christian C. Salvadó


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

like image 32
Massimo Avatar answered Oct 16 '22 06:10

Massimo