I'm using the following regular expression to validate CSS sizes:
([0-9]*\.?[0-9]+)(em|px|%)
The following sizes are therefore valid:
How can I change the regex to make the unit (em|px|%) optional to allow a number only?
You can simply add ? at the end to make the unit optional.
([0-9]*\.?[0-9]+)(em|px|%)?
As the unit is now optional, this pattern will allow numbers only entities as well. Be aware however, that doing some will also partial match the content making the following valid.
If this is an issue, then you can add the ^ start of string and $ end of line string pattern modifiers to restrict the check.
([0-9]*\.?[0-9]+)(em|px|%)?$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With