3

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...

1
  • can you please review the answers you have been given and accept the answer that helped you most or point out why none of them solve your problem. thanks.
    – Gordon
    Sep 2, 2012 at 12:52

4 Answers 4

2

@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

1
  • 1
    This could be shortened to /^\d\d+(\.\d+)?^\d/ But that might be a bit to unreadable.
    – Lobo
    Jun 25, 2012 at 22:40
1

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.

1

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]

0

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

Click here how for usage with PHP

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.