Home > Mobile >  How to validate string as a valid rem CSS value?
How to validate string as a valid rem CSS value?

Time:08-30

I'm doing some javascript validation on a passed in string value that should be in rem format. Looking for some guidance into Regex pattern that will match it.

This is what I have currently:

^\d*\.\d*(rem)$

However, this won't match for example (5rem). I'm sure I must be missing something simple. I'm also open to non-regex approaches.

CodePudding user response:

It's hard to know what possible values you need to match based on your question, but I think the problem could be that your current regex expects a decimal point to exist between two digits, or at least after the first.

If the rem value does not contain something all the time, you can use the ? or *. For the literal decimal match, you'll probably want to use ?.

Unless you need to match a group, the parenthesis are not necessary.

I would expect \d\.?\d*rem to work for you.

Regex101 is my preferred tool for testing expressions.

CodePudding user response:

You need to check floating point conditionally. Try this:

let pattern = /^-?\d*(\.\d )?(rem)$/
pattern.test("5rem"); // true
pattern.test("25rem"); // true
pattern.test("2.5rem"); // true
pattern.test("-2.5rem"); // true
pattern.test("5em"); // false

Not matching negative values:

let pattern = /^\d*(\.\d )?(rem)$/
pattern.test("5rem"); // true
pattern.test("25rem"); // true
pattern.test("2.5rem"); // true
pattern.test("-2.5rem"); // false
pattern.test("5em"); // false
  • Related