-2

I'm terrible at RegEx. Can anyone show a regex to use if I want to check a string for anything BUT digits 0-9, decimal point and percent sign?

I've tried this...

if (preg_match('/[^0-9.]+%/i',  $string)) {
     echo 'invalid';
}

but it's not working correctly. I have a input field which asks a user what the tax rate should be, and this is going to verify they have entered a VALID tax rate. I want them to enter it like "5.2%" rather than in decimal, and I will do the math on the back-end.

A VALID match would be "6%" or "5.2%" etc. A INVALID match would be "2" or "0.05" or "A"

Phil
  • 4,029
  • 9
  • 62
  • 107

2 Answers2

2

Look for a valid match, then invert it in the test:

if (!preg_match('/[\d.]%/', $string) {
    echo 'invalid';
}

But since this is supposed to test the whole string, not just look for a percentage anywhere in it, you need to anchor it:

if (!preg_match('/^[\d.]+%$/', $string) {
    echo 'invalid';
}

Note that this will allow something like .%. You probably should use something like Regular expression to match numbers with or without commas and decimals in text to match the number part.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • thank you - will accept as correct as soon as it lets me. – Phil Nov 08 '16 at 17:54
  • 1
    @anubhava No, that's why I suggested replacing `[\d.]` with the answer in that other question, because it should be invalid. – Barmar Nov 08 '16 at 18:04
1

You can match valid input and reverse your if condition:

if (preg_match('/\b\d*\.?\d+%/',  $string) === FALSE) {
     echo 'invalid';
}

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643