Reputation: 91
I use this preg_match
condition for matching positive, negative and decimal values
/^[0-9,-\.]{1,50}$/
But when I enter --34.000 it does not show error, when I enter 34...9868 it does not show error, what I want is that it must accept only positive, negative and decimal values.
Upvotes: 1
Views: 1899
Reputation: 83622
As yes123 stated, there are better ways to detect if a given input string is a numeric value. If you'd like to stick to regular expressions, the following might be OK for you:
/^-?[0-9]+(?:\.[0-9]+)?$/
Explanation:
^
)-
character (-?
); the ?
means "not required"[0-9]+
)(?:...)?
); ?:
means "do not capture the subpattern"
\.
); the .
needs to be escaped due to its special function[0-9]+
)$
)Upvotes: 4
Reputation: 10582
You need to split up your regular expression so that it only accepts the characters in the right places. For example:
/^[+\-]?([0-9]+,)*[0-9]+(\.[0-9]+)?$/
To explain this expression:
[+\-]?
: This checks for a + or - prefix to the number. It's completely optional, but can only be a + or -.
([0-9]+,)*
: This allows an optional set of comma-delimited numbers. This is for the thousands, millions etc.
[0-9]+
: This requires that the value contains at least some numbers
(\.[0-9]+)?
: Finally, this allows an optional decimal point with trailing numbers.
Upvotes: 2
Reputation: 6047
try this regex ^-?\d*\.?\d+$
i suppose it however cannot be limited to 50 chars
Upvotes: 0
Reputation: 48091
Better if you use something like is_numeric()
if yuo need to check if it's a number.
And your regex is totally broke because as now it can accept even only a string containing 50 dots
Upvotes: 4