Reputation: 7040
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
Reputation: 151
Easiest way is
$( "#myform" ).validate({
rules: {
field: {
required: true,
digits: true
}
}
});
ref : digits method | jQuery Validation Plugin --> https://jqueryvalidation.org/digits-method/
Upvotes: 4
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
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:
^
)\+?
)[0-9]*
)\.?
)[0-9]+
)$
)Upvotes: 39
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
Reputation: 39037
^\+?\d*.{0,1}\d+$
Gets you the ability to put a "+" in front of the number.
Upvotes: 0