I have the following code with zend framework:
$descuentoElement->addValidator(new Zend_Validate_Regex(array('pattern' => '/[0-9]+(.[0-9]+)?/')));
I want to validate double type inputs like either 1.2 or 4...not "4sd" but instead this pattern doesn't work fine...it allows writte "4s" ...Is there any answer or correct regex pattern for it...i would like a suggestion....thanks...
You have to anchor your regex and escape the dot:
^[0-9]+(\.[0-9]+)?$
The anchors (^
and $
) are necessary so it matches the complete string and not just an arbitrary substring. The dot is a special character in regexes and usually matches all other characters.
This is what you need:
^\d+(\.\d+)?$
^
: match only starting from the beginning of the string
$
: match only if your regexp matches the end of your string.
.
: dot need to be escaped o.w. it will match any character
\d
: matches any digit [0-9]
@Joey 's answer will work if you are matching entire lines, but you'll want to use something like
/[^0-9][0-9]+(\.[0-9]+)?[^0-9]/
if your targets aren't always on a line by themselves.
BREAKDOWN:
/
regex delimiter
[^0-9]
non-digit
[0-9]+
one or more digits
(
begin optional match
\.
dot character, escaped with \
[0-9]+
one or more digits
)?
end optional match; made optional with ?
[^0-9]
non-digit/
regex delimiter
Why don't you just use Zend_Validate_Float
?
Zend_Validate_Float allows you to validate if a given value contains a floating-point value. This validator validates also localized input.
Example from Reference Guide:
$validator = new Zend_Validate_Float();
$validator->isValid(1234.5); // returns true
$validator->isValid('10a01'); // returns false
$validator->isValid('1,234.5'); // returns true
If you still want a regex, the perl.org Website suggests this one for doubles:
{
^ (?&osg)\ * ( (?&int)(?&dec)? | (?&dec) ) (?: [eE](?&osg)(?&int) )? $
(?(DEFINE)
(?<osg>[-+]?) # optional sign
(?<int>\d++) # integer
(?<dec>\.(?&int)) # decimal fraction
)
}x