Svetlozar
Svetlozar

Reputation: 987

Regular expression for amount always returns true

I'm not very familiar with regex. Can someone tell me why I always get true for result? In regex101 this works.. This is my input dd(crb_is_valid_amount( '1234567.')); This is my function for validating amount:

function crb_is_valid_amount( $amount ) {
if ( preg_match( '/([\d]{1,6})(\.[\d]{2})?/', $amount ) )
{
 return true;
}
return false;
}

Upvotes: 0

Views: 78

Answers (2)

Syscall
Syscall

Reputation: 19764

You could use ^ and $ the specify the beginning and the end of the string

function crb_is_valid_amount( $amount ) {
    return preg_match('/^\d{1,6}(\.\d{2})?$/', $amount) ;
}

var_dump(crb_is_valid_amount('112.12')); // 1
var_dump(crb_is_valid_amount('1234567.')); // 0

Your original regular expression returns true for the second case, because '1234567.' contains 6 digits, but doesn't take care of what's after the 6 first digits. Using ^ and $ checks if the given string matches exactly with the expression, from start to end.

Means:

^\d{1,6}     # Begins with 1 to 6 digits,
(\.\d{2})?   # Optionally with a dot and 2 digits,
$            # End of given string (nothing after accepted).

Upvotes: 5

revo
revo

Reputation: 48751

You should use beginning and ending of string anchors along with \d{1,6}

function crb_is_valid_amount($amount) {
    return preg_match('/^\d{1,6}(?:\.\d{2})?$/', $amount) === 1 ? true : false;
}

Live demo

Upvotes: 3

Related Questions